# DESDEO documentation DESDEO 2 is an open-source Python framework for interactive multiobjective optimization. It provides modular, reusable components for implementing interactive decision-support methods, with a clear separation between algorithmic core-logic and user interfaces. DESDEO 2 represents a complete redesign of the original DESDEO software, motivated by practical challenges in building decision-support systems. The framework is built around three key layers: core-logic (algorithmic foundation), web-facing components, and end-user interfaces. Key architectural principles: - Explicit abstractions for problem modeling and method execution - Decoupling of algorithms from interface and deployment technology - Modular, composable components for interactive methods - Support for iterative interaction and preference modeling - Web-ready and service-oriented architecture The core-logic is fully self-contained and independent of any particular interface technology, addressing challenges in reproducibility, reuse, and extensibility. This stable foundation supports systematic experimentation while enabling future methodological development. # Usage documentation # DESDEO documentation Welcome to DESDEO's documentation! If you are new, keep reading. Otherwise, [you may jump to the quick-start section](#quick-start). ## DESDEO: the open-source software framework for interactive multiobjective optimization ### Introduction DESDEO is an open-source framework for interactive multiobjective optimization methods. The framework contains implementations of both scalarization- and population-based interactive methods. There are currently no other open-source software frameworks that focus solely on the implementation of interactive multiobjective optimization methods. The mission of DESDEO is to increase awareness of the benefits of interactive multiobjective optimization methods, make interactive methods openly available, and to function as *the* central hub for implementations of various interactive methods. Apart from existing methods, DESDEO offers various tools to facilitate the development of new methods and their application as well. Another important goal of DESDEO is to answer the needs of decision makers and practitioners when it comes to modeling and solving real-life multiobjective optimization problems. In the bigger picture, DESDEO will be composed of three major components: 1. The **core-logic**, which contains the algorithmic implementation of interactive methods, various tools related to multiobjective optimization, and means to model a variety of multiobjective optimization problems. The core-logic can be considered stable enough for use in research and applications. 1. The **web-API** (WIP), which implements a web-based application programming interface (API) to allow the use of the various functionalities found in DESDEO's core-logic through a web connection. The web-API implements also a database, which is a vital component for managing and enabling decision-support using the framework. **The web-API is currently under heavy development, and is subject to changes.** 1. The **web-GUI** (WIP), which implements a web-based interface for utilizing the interactive methods and tools for modeling and solving multiobjective optimization problems. > **The web-GUI relies heavily on the web-API, and is also being actively developed currently, and therefore subject to sudden changes.** For developing and experimenting with interactive multiobjective optimization methods on a "grass root" level, the **core-logic** provides the necessary tools. For deploying interactive methods, the **web-API** and the **web-GUI** play a central role. > Users interested in using or developing the web-API and/or web-GUI are highly encouraged to express such intentions on our [Discord server](https://discord.gg/uGCEgQTJyY)!. DESDEO is an open-source project and everybody is welcome to contribute! ### Core-logic: key features DESDEO's core-logic offers various features that can facilitate the application and development of new interactive multiobjective optimization methods. Some of the key features include, but are not limited to, - A powerful, pydantic-based, schema for modeling multiobjective optimization problem of various kinds. Including, analytically defined problems, data-based problems, surrogate-based problems, and simulation-based problems. Both continuous and (mixed-)integer problems are supported as well. - Support to interface to many popular and powerful optimization software for solving multiobjective optimization problems. Including Gurobi, various solvers from the COIN-OR project, and nevergrad, for instance. - A wide assortment of modular software components for implementing existing and new interactive multiobjective optimization methods. For example, many scalarization functions and evolutionary operators for multiobjective optimization are available. - An extensive documentation suitable for both newcomers to DESDEO and interactive multiobjective optimization in general, and seasoned veterans. For a complete overview of the interactive methods, algorithms, and tools currently implemented, see [Implemented methods and features](https://desdeo.readthedocs.io/en/latest/home/features/). ### Web-API: key features DESDEO's web-API is currently under active development. Once it stabilized, its key features will be listed here. In the meantime, the interested user can follow (and contribute!) the development progress of the web-API in [this issue](https://github.com/industrial-optimization-group/DESDEO/issues/245). ### Web-GUI: key features DESDEO's web-GUI is currently under active development. Once it stabilized, its key features will be listed here. In the meantime, the interested user can follow (and contribute!) the development progress of the web-API in [this issue](https://github.com/industrial-optimization-group/DESDEO/issues/251). ### Installation instructions (core-logic) DESDEO is available on PyPI to be installed via pip: ``` pip install desdeo ``` However, some of DESDEO's features rely on 3rd party optimizers, which should be available on your system. To read more on these, and on instructions on how to install the latest version of DESDEO directly from Github, [check out the documentation](https://desdeo.readthedocs.io/en/latest/howtoguides/installing/). ### Documentation Care has been taken to make sure DESDEO is well documented, making it accessible to both newcomers and seasoned users alike. [The documentation of DESDEO is available online.](https://desdeo.readthedocs.io/en/latest/) #### Documentation for LLMs An [`llms.txt`](https://desdeo.readthedocs.io/en/latest/llms.txt) and [`llms-full.txt`](https://desdeo.readthedocs.io/en/latest/llms-full.txt) file are available to appease our AI overlords. ### Contributing, reporting issues, and getting support As DESDEO is an open source-project, anybody is welcome to contribute. - **Contribute:** see [`CONTRIBUTING.md`](https://github.com/industrial-optimization-group/DESDEO/blob/master/CONTRIBUTING.md) for a quick start, and the [extensive contribution tutorial](https://desdeo.readthedocs.io/en/latest/tutorials/contributing/) in the documentation for the full development workflow. - **Report a bug or suggest an idea:** [open an issue](https://github.com/industrial-optimization-group/DESDEO/issues/new/choose) using one of the provided templates. - **Get help or discuss:** join the DESDEO Discord server [through this invite](https://discord.gg/uGCEgQTJyY). All participation in the project is governed by our [Code of Conduct](https://github.com/industrial-optimization-group/DESDEO/blob/master/CODE_OF_CONDUCT.md). ### License DESDEO is licensed under the MIT license. For more information, check the `LICENSE` file. ### Citing DESDEO To cite DESDEO, please include the following reference: [Misitano, G., Saini, B. S., Afsar, B., Shavazipour, B., & Miettinen, K. (2021). DESDEO: The modular and open source framework for interactive multiobjective optimization. IEEE Access, 9, 148277-148295.](https://doi.org/10.1109/ACCESS.2021.3123825) ``` @article{misitano2021desdeo, title={DESDEO: The modular and open source framework for interactive multiobjective optimization}, author={Misitano, Giovanni and Saini, Bhupinder Singh and Afsar, Bekir and Shavazipour, Babooshka and Miettinen, Kaisa}, journal={IEEE Access}, volume={9}, pages={148277--148295}, year={2021}, publisher={IEEE} } ``` **Note**: A new article describing the latest iteration of the framework, also known as *DESDEO 2.0*, is currently being prepared for submission to the [Journal of Open Source Software (JOSS)](https://joss.theoj.org/). The content of this repository's master branch is considered to be *DESDEO 2.0*. Once the JOSS paper is published it will become the preferred reference. Until then, please use the IEEE Access reference above. See the [Citing DESDEO](https://desdeo.readthedocs.io/en/latest/home/citing/) page and the [`CITATION.cff`](https://github.com/industrial-optimization-group/DESDEO/blob/master/CITATION.cff) file for up-to-date citation metadata. ### Funding Currently, DESDEO's development has been funded by projects granted by the [Research Council of Finland](https://www.aka.fi/en/). The most recent ones include: - INDENSYS (project 373063) - DESIDES (project 355346) - UTOPIA (project 352784) - DAEMON (project 322221) - DESDEO (project 287496) ## Quick-start - **About DESDEO** (Start here!) ______________________________________________________________________ Read about DESDEO and what it is about [DESDEO](https://desdeo.readthedocs.io/en/latest/home/index.md) - **Implemented methods and features** ______________________________________________________________________ See which interactive methods, algorithms, and tools are available [Features](https://desdeo.readthedocs.io/en/latest/home/features/index.md) - **Tutorials** ______________________________________________________________________ Learn about the central topics in DESDEO and how to contribute [Tutorials](https://desdeo.readthedocs.io/en/latest/tutorials/index.md) - **Explanation** ______________________________________________________________________ Understand how DESDEO works and what it offers [Explanation](https://desdeo.readthedocs.io/en/latest/explanation/index.md) - **Guides** ______________________________________________________________________ Get stuff done with DESDEO [Guides](https://desdeo.readthedocs.io/en/latest/howtoguides/index.md) ## API references - [**DESDEO Problem**](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/index.md) - [**DESDEO Tools**](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/index.md) - [**DESDEO MCDM**](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md) - [**DESDEO EMO**](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) # DESDEO General information about DESDEO can be found on the following pages: - **[About](https://desdeo.readthedocs.io/en/latest/home/about/index.md):** What is DESDEO about? (Start here!) - **[Structure](https://desdeo.readthedocs.io/en/latest/home/structure/index.md):** How is DESDEO structured? - **[Implemented methods and features](https://desdeo.readthedocs.io/en/latest/home/features/index.md):** What interactive methods and features are available? - **[Citing](https://desdeo.readthedocs.io/en/latest/home/citing/index.md):** How to cite DESDEO? ## What is DESDEO and multiobjective optimization? DESDEO is an open source software framework for interactive multiobjective optimization. Interactive methods are tools to support decision-making in problems with multiple conflicting objective functions, or in other words, multiobjective optimization problems. These problems have multiple optimal solutions, known as Pareto optimal solutions, which are represented by numerical vectors, and are therefore incomparable on a mathematical basis alone. To find the best solution among the Pareto optimal ones, preferences from a decision maker can be utilized. ## Interactive methods in multiobjective optimization Interactive methods are iterative by nature where a decision maker (who has substance knowledge about the problem being solved) can direct the solution process with one's preference information to find the most preferred balance between the objectives. In interactive methods, the amount of information to be considered at a time is limited and, thus, the cognitive load set on the decision maker is not too demanding. Furthermore, the decision maker learns about the interdependencies among the objectives and also the feasibility of their preferences. ## Mission The mission of DESDEO is to increase awareness of the benefits of interactive methods, and make interactive methods readily available and applicable. Thanks to the open architecture, interactive methods are easier to be utilized and further developed. The framework consists of reusable components that can be utilized for implementing new methods or modifying the existing methods. The framework is released under a permissive open source license. ## The research team behind DESDEO DESDEO has been an ongoing project driven forward by the Multiobjective Optimization group at the University of Jyväskylä in Finland. Many current and past members of the team have contributed to DESDEO. To learn more about the research team behind DESDEO, feel free to visit [their website](https://optgroup.it.jyu.fi). ## Where to go from here? **If none of the above made sense to you**, then do not worry! This documentation provides a primer on multiobjective optimization to get anyone with a basic understanding of mathematics and optimization quickly up to date on what interactive multiobjective optimization and interactive methods are. The primer can be accessed [here](https://desdeo.readthedocs.io/en/latest/tutorials/moo_primer/index.md). **If you are a seasoned veteran on multiobjective optimization**, and you want to start contributing to DESDEO right away, this documentation provides a tutorial on that [here](https://desdeo.readthedocs.io/en/latest/tutorials/contributing/index.md). # Citing DESDEO Have you found DESDEO useful in your work? While DESDEO is free and open-source, we still appreciate if its users could cite us when applicable! DESDEO has been developed over several years and has been described in more than one publication. To make sure you cite the most appropriate reference, please follow the guidance below. ## Which reference should I cite? - **The modern DESDEO framework (this software).** A dedicated software paper describing the current version of DESDEO is being prepared for the [Journal of Open Source Software (JOSS)](https://joss.theoj.org/). **Once it is published, it will be the preferred reference** and this page (and the [`CITATION.cff`](https://github.com/industrial-optimization-group/DESDEO/blob/master/CITATION.cff) file) will be updated accordingly. - **Until the JOSS paper is available**, please cite the IEEE Access (2021) paper given below as the general reference for DESDEO. About the earlier publications Two earlier publications are associated with DESDEO: - The **IEEE Access (2021)** paper documents an earlier (legacy) version of the framework. It is currently the recommended general reference until the JOSS paper is published. - The **2018 book chapter** *"DESDEO: An Open Framework for Interactive Multiobjective Optimization"* by Ojalehto and Miettinen ([doi:10.1007/978-3-319-99304-1_3](https://doi.org/10.1007/978-3-319-99304-1_3)) proposes the open framework for interactive multiobjective optimization that motivated DESDEO, rather than describing the current software. ## Recommended reference (until the JOSS paper is published) ``` @article{misitano2021desdeo, title={DESDEO: The modular and open source framework for interactive multiobjective optimization}, author={Misitano, Giovanni and Saini, Bhupinder Singh and Afsar, Bekir and Shavazipour, Babooshka and Miettinen, Kaisa}, journal={IEEE Access}, volume={9}, pages={148277--148295}, year={2021}, publisher={IEEE}, doi={10.1109/ACCESS.2021.3123825} } ``` You can also obtain machine-readable citation metadata from the [`CITATION.cff`](https://github.com/industrial-optimization-group/DESDEO/blob/master/CITATION.cff) file in the root of the repository. GitHub uses this file to provide a ready-to-use "Cite this repository" button. # Implemented methods and features This page gives an overview of what is currently implemented in DESDEO's core-logic, so you can quickly find the interactive methods, algorithms, and tools that are available and jump to the relevant guide and API reference. Each entry links to a how-to guide (where one exists) and to the corresponding section of the [API reference](https://desdeo.readthedocs.io/en/latest/api/index.md). Keeping this page current This page is maintained by hand. When adding a new interactive method, algorithm, operator, solver, or test problem to the core-logic, please add a row here as part of the same contribution. ## Interactive methods ### Scalarization-based (MCDM) methods | Method | Description | Reference | Guide | API | | ---------------------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | Reference Point Method | Projects a reference point onto the Pareto front using an achievement scalarizing function. | Wierzbicki, A. P. (1982). A mathematical basis for satisficing decision making. Mathematical Modelling, 3(5), 391-405. | [MCDM methods](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_utilize_mcdm_methods/index.md) | [mcdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md) | | Synchronous NIMBUS | Classification-based method where the decision maker improves/relaxes objectives. | Miettinen, K., & Mäkelä, M. M. (2006). Synchronous approach in interactive multiobjective optimization. European Journal of Operational Research, 170(3), 909-922. | [MCDM methods](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_utilize_mcdm_methods/index.md) | [mcdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md) | | G-NIMBUS | Group decision making variant of NIMBUS with a voting procedure. | No dedicated publication yet; group extension of NIMBUS (see the NIMBUS reference above). | [MCDM methods](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_utilize_mcdm_methods/index.md) | [mcdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md) | | NAUTILUS | Approaches the Pareto front from the nadir point without trading off. | Miettinen, K., Eskelinen, P., Ruiz, F., & Luque, M. (2010). NAUTILUS method: An interactive technique in multiobjective optimization based on the nadir point. European Journal of Operational Research, 206(2), 426-434. | [MCDM methods](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_utilize_mcdm_methods/index.md) | [mcdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md) | | NAUTILUS Navigator | Interactive navigation toward the Pareto front without trading off. | Ruiz, A. B., et al. (2019). NAUTILUS Navigator: free search interactive multiobjective optimization without trading-off. Journal of Global Optimization, 74(2), 213-231. | [NAUTILUS Navigator](https://desdeo.readthedocs.io/en/latest/howtoguides/nautilus_navigator/index.md) | [mcdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md) | | NAUTILI | Group decision making variant of the NAUTILUS family. | Pajasmaa, J., Saini, B. S., Shavazipour, B., Ruiz, F., Podkopaev, D., & Miettinen, K. (2026). NAUTILI: A trade-off-free interactive multiobjective optimization method for group decision making. Journal of Global Optimization. https://doi.org/10.1007/s10898-026-01617-6 | [NAUTILI](https://desdeo.readthedocs.io/en/latest/howtoguides/nautili/index.md) | [mcdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md) | | E-NAUTILUS | Computationally light NAUTILUS variant working from a precomputed set. | Ruiz, A. B., Sindhya, K., Miettinen, K., Ruiz, F., & Luque, M. (2015). E-NAUTILUS: A decision support system for complex multiobjective optimization problems based on the NAUTILUS method. European Journal of Operational Research, 246(1), 218-231. | [MCDM methods](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_utilize_mcdm_methods/index.md) | [mcdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md) | | Pareto Navigator | Interactive navigation over a polyhedral approximation of the Pareto front. | Eskelinen, P., et al. (2010). Pareto navigator for interactive nonlinear multiobjective optimization. OR Spectrum, 32, 211-227. | [Pareto Navigator](https://desdeo.readthedocs.io/en/latest/howtoguides/pareto_navigator/index.md) | [mcdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md) | ### Evolutionary (EMO) methods Evolutionary methods are configured through option helpers in `desdeo.emo.options.algorithms` and run with the templates in `desdeo.emo.methods.templates`. Mixed-integer variants are available for RVEA, NSGA-III, and IBEA. | Algorithm | Description | Reference | Guide | API | | --------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | | RVEA | Reference Vector Guided Evolutionary Algorithm. | Cheng, R., Jin, Y., Olhofer, M., & Sendhoff, B. (2016). A reference vector guided evolutionary algorithm for many-objective optimization. IEEE Transactions on Evolutionary Computation, 20(5), 773-791. | [Evolutionary algorithms](https://desdeo.readthedocs.io/en/latest/howtoguides/ea/index.md) | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | | NSGA-II | Non-dominated sorting genetic algorithm with crowding distance. | Deb, K., Pratap, A., Agarwal, S., & Meyarivan, T. (2002). A fast and elitist multiobjective genetic algorithm: NSGA-II. IEEE Transactions on Evolutionary Computation, 6(2), 182-197. | [Evolutionary algorithms](https://desdeo.readthedocs.io/en/latest/howtoguides/ea/index.md) | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | | NSGA-III | Reference-point based many-objective genetic algorithm. | Deb, K., & Jain, H. (2014). An evolutionary many-objective optimization algorithm using reference-point-based nondominated sorting approach, part I: solving problems with box constraints. IEEE Transactions on Evolutionary Computation, 18(4), 577-601. | [Evolutionary algorithms](https://desdeo.readthedocs.io/en/latest/howtoguides/ea/index.md) | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | | IBEA | Indicator-based evolutionary algorithm. | Zitzler, E., & Künzli, S. (2004). Indicator-based selection in multiobjective search. In Parallel Problem Solving from Nature (PPSN VIII), LNCS 3242, 832-842. Springer. | [Evolutionary algorithms](https://desdeo.readthedocs.io/en/latest/howtoguides/ea/index.md) | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | See [Configuring evolutionary algorithms](https://desdeo.readthedocs.io/en/latest/howtoguides/ea_options/index.md) and the [EMO Pydantic interface](https://desdeo.readthedocs.io/en/latest/api/EMO%20Options/index.md) for the available options. ## Building blocks and components ### Scalarization functions Available in `desdeo.tools.scalarization` (single decision maker) and `desdeo.tools.group_scalarization` (group decision making). Most come in both differentiable (`_diff`) and non-differentiable (`_nondiff`) forms. | Family | Single DM | Group | | -------------------------------------- | ------------------------- | ---------------------- | | Achievement scalarizing function (ASF) | yes (incl. generic forms) | yes (incl. aggregated) | | NIMBUS | yes | yes (incl. compromise) | | STOM | yes | yes (incl. aggregated) | | GUESS | yes | yes (incl. aggregated) | | Weighted sums | yes | | | Epsilon-constraint | yes | | | Objective as scalarization | yes | | | Desirability functions | yes | | | IOPIS | yes | | | Scenario-based | | yes | Guides: [Scalarization](https://desdeo.readthedocs.io/en/latest/explanation/scalarization/index.md), [Scalarization methods](https://desdeo.readthedocs.io/en/latest/explanation/scalarization_methods/index.md). API: [tools](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/index.md). ### Evolutionary operators | Component | Examples | API | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | Generators | random, Latin hypercube, binary/integer/mixed-integer, archive, seeded hybrid | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | | Crossover | simulated binary, blend-alpha, local, single-arithmetic, bounded exponential, single-point binary, uniform integer, uniform mixed-integer, composite | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | | Mutation | bounded polynomial, binary flip, integer/mixed-integer, power, non-uniform, self-adaptive Gaussian | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | | Selection | RVEA, NSGA-II, NSGA-III, IBEA selectors | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | | Scalar selection | tournament, roulette wheel | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | | Termination | max generations, max evaluations | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | | Archivers | non-dominated and feasibility archives | [emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) | Guide: [Implementing evolutionary algorithms](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_implement_ea/index.md). Explanation: [Crossover operators](https://desdeo.readthedocs.io/en/latest/explanation/crossover_operators/index.md). ### Solvers and interfaces DESDEO interfaces with several optimizers; `desdeo.tools.guess_best_solver` selects a suitable one automatically based on the problem. | Solver | Type | Notes | | -------------------------------------------------------------------------------------- | ---------------------- | --------------------------------- | | Gurobi (`GurobipySolver`, `PersistentGurobipySolver`) | LP / MIP | Commercial; license required | | Pyomo (`PyomoGurobiSolver`, `PyomoIpoptSolver`, `PyomoBonminSolver`, `PyomoCBCSolver`) | LP / NLP / MINLP / MIP | Via the Pyomo interface | | SciPy (`ScipyMinimizeSolver`, `ScipyDeSolver`) | NLP / global | `scipy.optimize` | | CVXPY (`CVXPYSolver`) | Convex | Requires a convex formulation | | Nevergrad (`NevergradGenericSolver`) | Derivative-free | Black-box optimization | | Proximal (`ProximalSolver`) | Data-based | For discrete, data-based problems | Guide: [Solvers](https://desdeo.readthedocs.io/en/latest/explanation/solvers/index.md). API: [tools](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/index.md). ### Quality indicators Available in `desdeo.tools.indicators_unary` and `desdeo.tools.indicators_binary`: hypervolume, IGD+, R2, R-metric, D-PHI, PHI+, additive epsilon (unary and binary), and related batch variants. API: [tools](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/index.md). ## Decision-support utilities | Feature | Description | Guide | API | | --------------------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | Artificial decision makers (ADMs) | Automated decision makers for benchmarking interactive methods (Chen et al. and Afsar et al. variants). | [Using ADMs](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_use_adms/index.md) | [adm](https://desdeo.readthedocs.io/en/latest/api/desdeo_adm/index.md) | | Group decision making (GDM) | Voting rules (majority, plurality), preference aggregation, and SCORE bands. | [GDM with SCORE bands](https://desdeo.readthedocs.io/en/latest/howtoguides/gdm_score/index.md) | [gdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_gdm/index.md) | | Explanations | SHAP-based explanations of solutions and Lagrange multiplier utilities. | | [explanations](https://desdeo.readthedocs.io/en/latest/api/desdeo_explanations/index.md) | | Representative solution sets | Generate a representative subset of solutions (iterative Pareto representer). | [Representative sets](https://desdeo.readthedocs.io/en/latest/howtoguides/IPR/index.md) | [tools](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/index.md) | ## Problem modeling and test problems ### Problem types DESDEO's [problem format](https://desdeo.readthedocs.io/en/latest/explanation/problem_format/index.md) supports analytical, data-based, simulation-based, and surrogate-based problems, with continuous and (mixed-)integer variables, as well as scenario-based problems. Guides: [How to define a problem](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_define_a_problem/index.md), [Problems with surrogates](https://desdeo.readthedocs.io/en/latest/howtoguides/advancedSurrogates/index.md), [Simulator support](https://desdeo.readthedocs.io/en/latest/explanation/simulator_support/index.md). API: [problem](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/index.md). ### Built-in test problems Available in `desdeo.problem.testproblems`. | Category | Problems | | ----------------------------- | -------------------------------------------------------------------------------- | | Benchmark suites | DTLZ (1, 2, 4), ZDT (1-4, 6), RE (21-24) | | Engineering design | multiobjective welded beam (6 variants), rocket injector design | | Real-world | river pollution, forest management, Spanish sustainability, summer cabin battery | | Combinatorial / mixed-integer | knapsack, MOMIP | | Pedagogical / synthetic | various `simple_*` problems, the cake problem | Guide: [Test problems](https://desdeo.readthedocs.io/en/latest/explanation/test_problems/index.md). API: [problem](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/index.md). # The structure of DESDEO In the big picture, DESDEO is not just meant to be a collection of interactive multiobjective optimization methods, but a **full stack** solution (which can be run as an application) to provide decision-support for decision makers to tackle real-life multiobjective optimization problems by utilizing interactive methods. Being a full stack solution, it consists of three main components: 1. [**the core-logic**](#the-core-logic), 1. [**the web-API**](#the-web-api), and 1. [**the web-GUI**](#the-web-gui). We will describe each of these components in the following sections. ## The core-logic The core-logic of DESDEO is implemented in Python and contains tools and functionalities for modeling multiobjective optimization problems and implementing interactive multiobjective optimization methods. This also includes a plethora of other functionalities that are required, such as scalarization utilities and (programmatic) interfaces to existing optimization software. The core-logic itself consists of **four main modules**. The first of these is `desdeo.problem`, which has functions and classes for problem modeling, parsing, and evaluation. In addition, the module contains also pre-defined test problems that can be utilized to readily benchmark and pilot, e.g., interactive methods. [The problem model](https://desdeo.readthedocs.io/en/latest/explanation/problem_format/index.md) is also defined in `desdeo.problem`, which is at the very core when it comes to how multiobjective optimization problems are handled in the core-logic. The second main module is `desdeo.tools`. This module contains additional utilities, which can be considered to be generic, and not specific to any type of interactive methods (such as MCDM or EMO, covered next). This includes scalarization and solver interfaces to existing optimization algorithms, for example, Gurobi, or utilities, such as the payoff-table method. Next, we have the first of the main modules that contain logic for implementing interactive multiobjective optimization methods, `desdeo.mcdm`. The name *MCDM* refers to interactive methods that have been inspired by more traditional approaches in the field of multi-criteria decision-making. In practice, these are interactive methods that often rely on scalarization in one way or another, and utilize exact optimizers to generate solutions that can be guaranteed (to a varying degree) to be Pareto optimal. The methods have been implemented in a modular fashion, meaning, that relevant steps of different methods are implemented as functions. These functions can be mixed and matched to create existing interactive methods, or completely new ones with relative little effort. Lastly, the second of the main modules containing logic for implementing interactive methods is `desdeo.emo`. This module is for evolutionary multiobjective optimization methods, which utilize heuristic to improve a population of solutions iteratively. Unlike MCDM methods, EMO (evolutionary multiobjective optimization) methods are implemented using [templates and publish-subscribe patterns](https://desdeo.readthedocs.io/en/latest/explanation/templates_and_pub_sub/index.md). Nonetheless, the `desdeo.emo` contains many different cross-over, mutation, selection, and termination operators, which can be combined in different way to create existing or new EMO methods. Apart from the four main modules, the core-logic includes additional modules, such as `desdeo.adm` (artificial decision makers for benchmarking interactive methods), `desdeo.gdm` (group decision making), and `desdeo.explanations` (explainability tools). A full overview of the available methods and features is given on the [Implemented methods and features](https://desdeo.readthedocs.io/en/latest/home/features/index.md) page. The main modules, and others, can be found in the `/desdeo/` directory of the source tree. ## The web-API The web-API (application programming interface) is a web interface that allows software and applications to utilize DESDEO through HTTP endpoints over a web connection. Its main purpose is to enable other applications to have access to the core-logic of DESDEO. In addition, the web-API introduced a **database**. This allows DESDEO to handle users and users sessions, which is critical for building decision-support tools. WIP The web-API is currently under heavy development. Be free to explore it and contribute, but understand things will be changing fast and nothing is stable! If you are interested in contributing to the web-API, please check out [this issue](https://github.com/industrial-optimization-group/DESDEO/issues/245) and be sure to hop on our [Discord server](https://discord.gg/uGCEgQTJyY) for additional support! The web-API can be found in the directory `desdeo/api/` in the project source tree. ## The web-GUI The web-GUI is the frontend part of DESDEO. It implements an interface, which allows users to utilize DESDEO through a graphical user interface. The web-GUI is in the early stages of development. WIP The web-GUI is currently under heavy development. Be free to explore it and contribute, but understand things will be changing fast and nothing is stable! If you are interested in contributing to the web-GUI, please check out [this issue](https://github.com/industrial-optimization-group/DESDEO/issues/251) and be sure to hop on our [Discord server](https://discord.gg/uGCEgQTJyY) for additional support! The web-GUI can be found in the directory `webui/` in the project source tree. # Core-Logic API Reference The API reference provides the documentation of the individual functions, classes, and methods found in the core-logic. You may also use the search function provided at the top of the page to quickly jump to any relevant documentation. ## Core modules The following references cover the core modules of DESDEO. - **[desdeo.problem](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/index.md):** Module containing tools and utilities to model and evaluate multiobjective optimization problems. - **[desdeo.mcdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_mcdm/index.md):** Module containing components for building interactive *MCDM inspired* methods. - **[desdeo.emo](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md):** Module containing components for building evolutionary interactive methods. - **[desdeo.tools](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/index.md):** Module containing miscellaneous tools and utilities utilized across the core-logic. ## Other modules The following references cover additional modules of DESDEO. - **[desdeo-adm](https://desdeo.readthedocs.io/en/latest/api/desdeo_adm/index.md):** Module containing artificial decision makers (ADMs) for automated testing and benchmarking of interactive methods. - **[desdeo-gdm](https://desdeo.readthedocs.io/en/latest/api/desdeo_gdm/index.md):** Module containing tools for group decision making, including voting rules and preference aggregation. - **[desdeo-explanations](https://desdeo.readthedocs.io/en/latest/api/desdeo_explanations/index.md):** Module containing tools to generate and analyze explanations of solutions, such as SHAP-based explanations and Lagrange multiplier utilities. This page documents the Pydantic interfaces for configuring Evolutionary Multi-Objective Optimization (EMO) algorithms in DESDEO. Essentially, create a complete EMOOptions model by specifying options for the various components of the algorithm. Pass the created model, along with the problem to be solved, to emo_constructor to create an instance of the desired algorithm. Popular pre-configured EMO methods include NSGA-III, RVEA, MOEA/D, and IBEA. You can find the actual implementation of these components in the [EMO](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/index.md) page. ## Algorithms Define popular MOEAs as Pydantic models. ### \_mixed_integer ``` _mixed_integer( options: EMOOptions, algorithm_name: str ) -> EMOOptions ``` Swap a continuous configuration's variation and initialization for the mixed-integer operators. Source code in `desdeo/emo/options/algorithms.py` ``` def _mixed_integer(options: EMOOptions, algorithm_name: str) -> EMOOptions: """Swap a continuous configuration's variation and initialization for the mixed-integer operators.""" template = options.template template.algorithm_name = algorithm_name template.crossover = UniformMixedIntegerCrossoverOptions() template.mutation = MixedIntegerRandomMutationOptions() template.generator = RandomMixedIntegerGeneratorOptions(n_points=template.generator.n_points) template.repair = NoRepairOptions(name="NoRepair") return options ``` ### agemoea2_mixed_integer_options ``` agemoea2_mixed_integer_options() -> EMOOptions ``` Get default AGE-MOEA-II options for mixed integer problems as a Pydantic model. References A. Panichella, "An Improved Pareto Front Modeling Algorithm for Large-scale Many-Objective Optimization," in Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '22), Boston, MA, USA: ACM, Jul. 2022, pp. 565-573, doi: 10.1145/3512290.3528732. Returns: | Name | Type | Description | | ------------ | ------------ | ------------------------------------------------------------------ | | `EMOOptions` | `EMOOptions` | The default AGE-MOEA-II mixed integer options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def agemoea2_mixed_integer_options() -> EMOOptions: """Get default AGE-MOEA-II options for mixed integer problems as a Pydantic model. References: A. Panichella, "An Improved Pareto Front Modeling Algorithm for Large-scale Many-Objective Optimization," in Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '22), Boston, MA, USA: ACM, Jul. 2022, pp. 565-573, doi: 10.1145/3512290.3528732. Returns: EMOOptions: The default AGE-MOEA-II mixed integer options as a Pydantic model. """ return _mixed_integer(agemoea2_options(), "AGE-MOEA-II_Mixed_Integer") ``` ### agemoea2_options ``` agemoea2_options() -> EMOOptions ``` Get default AGE-MOEA-II options as a Pydantic model. Not AGE-MOEA: the paper below compares the two on 17 WFG and SMOP problems at 3, 6 and 9 objectives, and AGE-MOEA-II is significantly better on 41 of the 51 cases and worse on 2. References A. Panichella, "An Improved Pareto Front Modeling Algorithm for Large-scale Many-Objective Optimization," in Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '22), Boston, MA, USA: ACM, Jul. 2022, pp. 565-573, doi: 10.1145/3512290.3528732. A. Panichella, "An Adaptive Evolutionary Algorithm based on Non-Euclidean Geometry for Many-objective Optimization," in Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '19), Prague, Czech Republic: ACM, Jul. 2019, pp. 595-603, doi: 10.1145/3321707.3321839. Returns: | Name | Type | Description | | ------------ | ------------ | ---------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default AGE-MOEA-II options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def agemoea2_options() -> EMOOptions: """Get default AGE-MOEA-II options as a Pydantic model. Not AGE-MOEA: the paper below compares the two on 17 WFG and SMOP problems at 3, 6 and 9 objectives, and AGE-MOEA-II is significantly better on 41 of the 51 cases and worse on 2. References: A. Panichella, "An Improved Pareto Front Modeling Algorithm for Large-scale Many-Objective Optimization," in Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '22), Boston, MA, USA: ACM, Jul. 2022, pp. 565-573, doi: 10.1145/3512290.3528732. A. Panichella, "An Adaptive Evolutionary Algorithm based on Non-Euclidean Geometry for Many-objective Optimization," in Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '19), Prague, Czech Republic: ACM, Jul. 2019, pp. 595-603, doi: 10.1145/3321707.3321839. Returns: EMOOptions: The default AGE-MOEA-II options as a Pydantic model. """ return EMOOptions( preference=None, template=Template2Options( algorithm_name="AGE-MOEA-II", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=30, # eta_c = 30, Table 1 # Table 1's p_c = 1 is per pair; the per-variable rate is Deb and Agrawal's 0.5. pair_xover_probability=1.0, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, # eta_m = 20, Table 1 mutation_probability=None, # p_m = 1/n ), selection=AGEMOEA2SelectorOptions( name="AGEMOEA2Selector", # Table 1 uses 200, 300 and 400 solutions at 3, 6 and 9 objectives. population_size=100, ), # AGE-MOEA's binary tournament, by front and then survival score (2019, Section 3.1). mate_selection=TournamentSelectionOptions( name="TournamentSelection", tournament_size=2, winner_size=100, ), # The paper starts from a random population (Algorithm 2, line 2). LHS makes it lose parts of a # biased front less often: on 3-objective DTLZ4 it reached the full front on 10 of 20 seeds, # against 4 of 20 from a random start. generator=LHSGeneratorOptions( name="LHSGenerator", n_points=100, ), repair=ClipRepairOptions(), # Table 1 runs 200 iterations. termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### emo_constructor ``` emo_constructor( emo_options: EMOOptions, problem: Problem, external_check: Callable[[], bool] | None = None, ) -> tuple[Callable[[], EMOResult], ConstructorExtras] ``` Construct an evolutionary algorithm from the given options. Parameters: | Name | Type | Description | Default | | ---------------- | ---------------------- | ---------------------------------- | --------------------------------------------------------------------------------------------- | | `emo_options` | `EMOOptions` | The options for the EMO algorithm. | *required* | | `problem` | `Problem` | The optimization problem to solve. | *required* | | `external_check` | \`Callable\[[], bool\] | None\` | A callable that returns True if the algorithm should stop, False otherwise. By default, None. | Returns: | Type | Description | | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | `Callable[[], EMOResult]` | tuple\[Callable\[[], EMOResult\], ConstructorExtras\]: A tuple containing the template function | | `ConstructorExtras` | and extra information such as the (possibly modified) problem, publisher, and archive. Run the template | | `tuple[Callable[[], EMOResult], ConstructorExtras]` | function to execute the algorithm. | Raises: | Type | Description | | ---------------------- | ----------------------------------------- | | `InvalidTemplateError` | If the template configuration is invalid. | Source code in `desdeo/emo/options/templates.py` ``` def emo_constructor( emo_options: EMOOptions, problem: Problem, external_check: Callable[[], bool] | None = None ) -> tuple[Callable[[], EMOResult], ConstructorExtras]: """Construct an evolutionary algorithm from the given options. Args: emo_options (EMOOptions): The options for the EMO algorithm. problem (Problem): The optimization problem to solve. external_check (Callable[[], bool] | None): A callable that returns True if the algorithm should stop, False otherwise. By default, None. Returns: tuple[Callable[[], EMOResult], ConstructorExtras]: A tuple containing the template function and extra information such as the (possibly modified) problem, publisher, and archive. Run the template function to execute the algorithm. Raises: InvalidTemplateError: If the template configuration is invalid. """ publisher = Publisher() template = emo_options.template if template.name == "TemplateXLEMOO": problem_, selector_options = _xlemoo_preference_handler( preference=emo_options.preference, problem=problem, selection=template.selection, scalarization=template.scalarization, ) else: problem_, selector_options = preference_handler( preference=emo_options.preference, problem=problem, selection=template.selection ) evaluator = EMOEvaluator(problem=problem_, publisher=publisher, verbosity=template.verbosity) if template.name == "TemplateXLEMOO": selector = scalar_selector_constructor( options=selector_options, publisher=publisher, verbosity=template.verbosity, seed=template.seed, problem=problem_, ) else: selector = selection_constructor( problem=problem_, options=selector_options, publisher=publisher, verbosity=template.verbosity, seed=template.seed, ) generator_options = template.generator if template.name == "TemplateMOEAD" and "n_points" in type(generator_options).model_fields: # MOEA/D keeps exactly one solution per weight vector. generator_options = generator_options.model_copy(update={"n_points": selector.number_of_subproblems}) generator = generator_constructor( problem=problem_, options=generator_options, evaluator=evaluator, publisher=publisher, verbosity=template.verbosity, seed=template.seed, ) crossover = crossover_constructor( problem=problem_, options=template.crossover, publisher=publisher, verbosity=template.verbosity, seed=template.seed, ) mutation = mutation_constructor( problem=problem_, options=template.mutation, publisher=publisher, verbosity=template.verbosity, seed=template.seed, ) terminator = terminator_constructor( options=template.termination, publisher=publisher, external_check=external_check, ) repair = repair_constructor(options=template.repair, problem=problem_) components = { "evaluator": evaluator, "generator": generator, "crossover": crossover, "mutation": mutation, "selection": selector, "terminator": terminator, } if template.use_archive: archive = NonDominatedArchive( problem=problem_, publisher=publisher, ) components["archive"] = archive if template.name == "Template2": scalar_selector = scalar_selector_constructor( options=template.mate_selection, publisher=publisher, verbosity=template.verbosity, seed=template.seed, problem=problem_, ) components["mate_selection"] = scalar_selector learning_operator: LearningModeOperator | None = None if template.name == "TemplateXLEMOO": if not isinstance(selector, ElitistSelection): raise InvalidTemplateError("XLEMOO requires an ElitistSelection scalar selector.") learning_operator = LearningModeOperator( problem=problem_, selector=selector, publisher=publisher, verbosity=template.verbosity, h_split=template.h_split, l_split=template.l_split, instantiation_factor=template.instantiation_factor, seed=template.seed, ) components["learning_operator"] = learning_operator consistency = publisher.check_consistency() if not consistency[0]: raise InvalidTemplateError(f"Inconsistent template configuration. See details:\n {consistency[1]}") archive = components.pop("archive", None) template_funcs = { "Template1": template1, "Template2": template2, "TemplateXLEMOO": template_xlemoo, "Template3": template3, "TemplateMOEAD": template_moead, } if template.name == "TemplateXLEMOO": constructor_extras = ConstructorExtras( problem=problem_, publisher=publisher, archive=archive, learning_operator=learning_operator, ) return ( partial( template_xlemoo, **components, repair=repair, n_darwin_per_cycle=template.n_darwin_per_cycle, n_learning_per_cycle=template.n_learning_per_cycle, ), constructor_extras, ) constructor_extras = ConstructorExtras(problem=problem_, publisher=publisher, archive=archive) if template.name in ("Template3", "TemplateMOEAD"): components["seed"] = template.seed return (partial(template_funcs[template.name], **components, repair=repair), constructor_extras) ``` ### hype_mixed_integer_options ``` hype_mixed_integer_options() -> EMOOptions ``` Get default HypE options for mixed integer problems as a Pydantic model. References J. Bader and E. Zitzler, "HypE: An Algorithm for Fast Hypervolume-Based Many-Objective Optimization," Evolutionary Computation, vol. 19, no. 1, pp. 45-76, Mar. 2011, doi: 10.1162/EVCO_a_00009. Returns: | Name | Type | Description | | ------------ | ------------ | ----------------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default HypE mixed integer options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def hype_mixed_integer_options() -> EMOOptions: """Get default HypE options for mixed integer problems as a Pydantic model. References: J. Bader and E. Zitzler, "HypE: An Algorithm for Fast Hypervolume-Based Many-Objective Optimization," Evolutionary Computation, vol. 19, no. 1, pp. 45-76, Mar. 2011, doi: 10.1162/EVCO_a_00009. Returns: EMOOptions: The default HypE mixed integer options as a Pydantic model. """ return _mixed_integer(hype_options(), "HypE_Mixed_Integer") ``` ### hype_options ``` hype_options() -> EMOOptions ``` Get default HypE options as a Pydantic model. The paper's experiments use a population of 50, 10 000 Monte Carlo samples, SBX with eta = 20 and polynomial mutation, with the rates of Deb et al.'s DTLZ study (crossover 1.0 per pair, mutation 1/n). The hypervolume fitness is exact up to three objectives. References J. Bader and E. Zitzler, "HypE: An Algorithm for Fast Hypervolume-Based Many-Objective Optimization," Evolutionary Computation, vol. 19, no. 1, pp. 45-76, Mar. 2011, doi: 10.1162/EVCO_a_00009. Implemented from the technical report version, TIK Report 286, ETH Zurich, 2008, doi: 10.3929/ethz-a-005703480. Returns: | Name | Type | Description | | ------------ | ------------ | --------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default HypE options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def hype_options() -> EMOOptions: """Get default HypE options as a Pydantic model. The paper's experiments use a population of 50, 10 000 Monte Carlo samples, SBX with eta = 20 and polynomial mutation, with the rates of Deb et al.'s DTLZ study (crossover 1.0 per pair, mutation 1/n). The hypervolume fitness is exact up to three objectives. References: J. Bader and E. Zitzler, "HypE: An Algorithm for Fast Hypervolume-Based Many-Objective Optimization," Evolutionary Computation, vol. 19, no. 1, pp. 45-76, Mar. 2011, doi: 10.1162/EVCO_a_00009. Implemented from the technical report version, TIK Report 286, ETH Zurich, 2008, doi: 10.3929/ethz-a-005703480. Returns: EMOOptions: The default HypE options as a Pydantic model. """ return EMOOptions( preference=None, template=Template2Options( algorithm_name="HypE", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=20, pair_xover_probability=1.0, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, ), selection=HypESelectorOptions( name="HypESelector", population_size=50, n_samples=10_000, exact_max_objectives=3, normalised_reference_point_component=1.1, ), mate_selection=TournamentSelectionOptions( name="TournamentSelection", tournament_size=2, winner_size=50, ), generator=RandomGeneratorOptions( name="RandomGenerator", n_points=50, ), repair=ClipRepairOptions(), # The paper runs 200 generations. termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### ibea_mixed_integer_options ``` ibea_mixed_integer_options() -> EMOOptions ``` Get default IBEA options for mixed integer problems as a Pydantic model. References Zitzler, E., Künzli, S. (2004). Indicator-Based Selection in Multiobjective Search. In: Yao, X., et al. Parallel Problem Solving from Nature - PPSN VIII. PPSN 2004. Lecture Notes in Computer Science, vol 3242. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-30217-9_84 Returns: | Name | Type | Description | | ------------ | ------------ | ---------------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default IBEA mixed integer options as a Pydantic model | Source code in `desdeo/emo/options/algorithms.py` ``` def ibea_mixed_integer_options() -> EMOOptions: """Get default IBEA options for mixed integer problems as a Pydantic model. References: Zitzler, E., Künzli, S. (2004). Indicator-Based Selection in Multiobjective Search. In: Yao, X., et al. Parallel Problem Solving from Nature - PPSN VIII. PPSN 2004. Lecture Notes in Computer Science, vol 3242. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-30217-9_84 Returns: EMOOptions: The default IBEA mixed integer options as a Pydantic model """ return EMOOptions( preference=None, template=Template2Options( algorithm_name="IBEA_Mixed_Integer", crossover=UniformMixedIntegerCrossoverOptions(), mutation=MixedIntegerRandomMutationOptions(), selection=IBEASelectorOptions( name="IBEASelector", binary_indicator="eps", kappa=0.05, population_size=100, ), mate_selection=TournamentSelectionOptions( name="TournamentSelection", tournament_size=2, winner_size=100, ), generator=RandomMixedIntegerGeneratorOptions(n_points=100), repair=NoRepairOptions( name="NoRepair", ), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### ibea_options ``` ibea_options() -> EMOOptions ``` Get default IBEA options as a Pydantic model. References Zitzler, E., Künzli, S. (2004). Indicator-Based Selection in Multiobjective Search. In: Yao, X., et al. Parallel Problem Solving from Nature - PPSN VIII. PPSN 2004. Lecture Notes in Computer Science, vol 3242. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-30217-9_84 Returns: | Name | Type | Description | | ------------ | ------------ | --------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default IBEA options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def ibea_options() -> EMOOptions: """Get default IBEA options as a Pydantic model. References: Zitzler, E., Künzli, S. (2004). Indicator-Based Selection in Multiobjective Search. In: Yao, X., et al. Parallel Problem Solving from Nature - PPSN VIII. PPSN 2004. Lecture Notes in Computer Science, vol 3242. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-30217-9_84 Returns: EMOOptions: The default IBEA options as a Pydantic model. """ return EMOOptions( preference=None, template=Template2Options( algorithm_name="IBEA", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=20, # Note that the operator defaults are different in Template2 pair_xover_probability=1.0, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, ), selection=IBEASelectorOptions( name="IBEASelector", binary_indicator="eps", kappa=0.05, population_size=100, ), mate_selection=TournamentSelectionOptions( name="TournamentSelection", tournament_size=2, winner_size=100, ), generator=LHSGeneratorOptions( name="LHSGenerator", n_points=100, ), repair=ClipRepairOptions(), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### modified_wasfga_mixed_integer_options ``` modified_wasfga_mixed_integer_options() -> EMOOptions ``` Get default Modified WASF-GA options for mixed integer problems as a Pydantic model. References R. Saborido, A. B. Ruiz, M. Luque and K. Miettinen, "IRA-EMO: Interactive Method Using Reservation and Aspiration Levels for Evolutionary Multiobjective Optimization," in Evolutionary Multi-Criterion Optimization (EMO 2019), LNCS vol. 11411, Springer, 2019, pp. 618-630, doi: 10.1007/978-3-030-12598-1_49. Returns: | Name | Type | Description | | ------------ | ------------ | ----------------------------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default Modified WASF-GA mixed integer options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def modified_wasfga_mixed_integer_options() -> EMOOptions: """Get default Modified WASF-GA options for mixed integer problems as a Pydantic model. References: R. Saborido, A. B. Ruiz, M. Luque and K. Miettinen, "IRA-EMO: Interactive Method Using Reservation and Aspiration Levels for Evolutionary Multiobjective Optimization," in Evolutionary Multi-Criterion Optimization (EMO 2019), LNCS vol. 11411, Springer, 2019, pp. 618-630, doi: 10.1007/978-3-030-12598-1_49. Returns: EMOOptions: The default Modified WASF-GA mixed integer options as a Pydantic model. """ return _mixed_integer(modified_wasfga_options(), "ModifiedWASFGA_Mixed_Integer") ``` ### modified_wasfga_options ``` modified_wasfga_options() -> EMOOptions ``` Get default Modified WASF-GA options as a Pydantic model. Modified WASF-GA is the evolutionary part of IRA-EMO (Step 5 of the paper's algorithm). It looks for solutions between an aspiration point and a reservation point, which are given as a `DesirableRangesOptions` preference with `method="Modified WASF-GA"`. Without a preference it uses the ideal and nadir points estimated from the run, as Global WASF-GA does. The rest of IRA-EMO (showing the decision maker the solutions between the two points, and asking for new levels) is left to the caller. The settings are those of the authors' reference code (`IRAEMO_Settings`, real-coded problems): population and weight vectors 100, 200 generations, a random initial population, SBX and polynomial mutation with distribution indices of 20, and a binary tournament by Pareto dominance (jMetal's `BinaryTournament2`). The paper's own example used a population of 50 for 100 generations, on a mixed-integer problem. Where the paper and the code disagree, this follows the code, except for the defects listed in `ModifiedWASFGASelector`. References R. Saborido, A. B. Ruiz, M. Luque and K. Miettinen, "IRA-EMO: Interactive Method Using Reservation and Aspiration Levels for Evolutionary Multiobjective Optimization," in Evolutionary Multi-Criterion Optimization (EMO 2019), LNCS vol. 11411, Springer, 2019, pp. 618-630, doi: 10.1007/978-3-030-12598-1_49. A. B. Ruiz, R. Saborido and M. Luque, "A preference-based evolutionary algorithm for multiobjective optimization: the weighting achievement scalarizing function genetic algorithm," Journal of Global Optimization, vol. 62, no. 1, pp. 101-129, 2015, doi: 10.1007/s10898-014-0214-y. Returns: | Name | Type | Description | | ------------ | ------------ | --------------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default Modified WASF-GA options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def modified_wasfga_options() -> EMOOptions: """Get default Modified WASF-GA options as a Pydantic model. Modified WASF-GA is the evolutionary part of IRA-EMO (Step 5 of the paper's algorithm). It looks for solutions between an aspiration point and a reservation point, which are given as a `DesirableRangesOptions` preference with `method="Modified WASF-GA"`. Without a preference it uses the ideal and nadir points estimated from the run, as Global WASF-GA does. The rest of IRA-EMO (showing the decision maker the solutions between the two points, and asking for new levels) is left to the caller. The settings are those of the authors' reference code (`IRAEMO_Settings`, real-coded problems): population and weight vectors 100, 200 generations, a random initial population, SBX and polynomial mutation with distribution indices of 20, and a binary tournament by Pareto dominance (jMetal's `BinaryTournament2`). The paper's own example used a population of 50 for 100 generations, on a mixed-integer problem. Where the paper and the code disagree, this follows the code, except for the defects listed in `ModifiedWASFGASelector`. References: R. Saborido, A. B. Ruiz, M. Luque and K. Miettinen, "IRA-EMO: Interactive Method Using Reservation and Aspiration Levels for Evolutionary Multiobjective Optimization," in Evolutionary Multi-Criterion Optimization (EMO 2019), LNCS vol. 11411, Springer, 2019, pp. 618-630, doi: 10.1007/978-3-030-12598-1_49. A. B. Ruiz, R. Saborido and M. Luque, "A preference-based evolutionary algorithm for multiobjective optimization: the weighting achievement scalarizing function genetic algorithm," Journal of Global Optimization, vol. 62, no. 1, pp. 101-129, 2015, doi: 10.1007/s10898-014-0214-y. Returns: EMOOptions: The default Modified WASF-GA options as a Pydantic model. """ return EMOOptions( preference=None, template=Template2Options( algorithm_name="ModifiedWASFGA", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=20, # jMetal's SBXCrossover crosses a pair with probability 0.9, then each variable with # probability 0.5, and swaps the two values between the offspring with probability 0.5. pair_xover_probability=0.9, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, # 1 / n ), selection=ModifiedWASFGASelectorOptions( name="ModifiedWASFGASelector", population_size=100, # the reference code sets the number of weight vectors to the same value ), mate_selection=TournamentSelectionOptions( name="TournamentSelection", tournament_size=2, winner_size=100, comparison="dominance", ), generator=RandomGeneratorOptions( name="RandomGenerator", n_points=100, ), repair=ClipRepairOptions(), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=200, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### moead_de_options ``` moead_de_options() -> EMOOptions ``` Get default MOEA/D-DE options as a Pydantic model. MOEA/D with a differential evolution operator whose base vector is the subproblem's own solution, mating with the whole population with probability 1 - delta, and at most n_r replacements per offspring. The paper resets a variable that leaves its bounds to a random value inside them (Step 2.3). This configuration clips it instead, as DESDEO's differential evolution operator, PlatEMO and jMetal all do. References H. Li and Q. Zhang, "Multiobjective Optimization Problems With Complicated Pareto Sets, MOEA/D and NSGA-II," IEEE Transactions on Evolutionary Computation, vol. 13, no. 2, pp. 284-302, Apr. 2009, doi: 10.1109/TEVC.2008.925798. Returns: | Name | Type | Description | | ------------ | ------------ | -------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default MOEA/D-DE options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def moead_de_options() -> EMOOptions: """Get default MOEA/D-DE options as a Pydantic model. MOEA/D with a differential evolution operator whose base vector is the subproblem's own solution, mating with the whole population with probability 1 - delta, and at most n_r replacements per offspring. The paper resets a variable that leaves its bounds to a random value inside them (Step 2.3). This configuration clips it instead, as DESDEO's differential evolution operator, PlatEMO and jMetal all do. References: H. Li and Q. Zhang, "Multiobjective Optimization Problems With Complicated Pareto Sets, MOEA/D and NSGA-II," IEEE Transactions on Evolutionary Computation, vol. 13, no. 2, pp. 284-302, Apr. 2009, doi: 10.1109/TEVC.2008.925798. Returns: EMOOptions: The default MOEA/D-DE options as a Pydantic model. """ return EMOOptions( preference=None, template=TemplateMOEADOptions( algorithm_name="MOEA/D-DE", crossover=DifferentialEvolutionCrossoverOptions( name="DifferentialEvolutionCrossover", scaling_factor=0.5, xover_probability=1.0, base_vector="target", # Step 2.2 sets r1 = i ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, # p_m = 1/n ), selection=MOEADSelectorOptions( name="MOEADSelector", # The paper uses N = 300 weight vectors at two objectives (H = 299) and 595 at three # (H = 33), on problems built to be hard to converge on. reference_vector_options=ReferenceVectorOptions( adaptation_frequency=0, creation_type="simplex", vector_type="planar", lattice_resolution=None, number_of_vectors=100, ), neighbourhood_size=20, neighbourhood_probability=0.9, max_replacements=2, aggregation="tchebycheff", ), generator=RandomGeneratorOptions( name="RandomGenerator", n_points=100, ), repair=ClipRepairOptions(), # The paper runs 500 generations. termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### moead_mixed_integer_options ``` moead_mixed_integer_options() -> EMOOptions ``` Get default MOEA/D options for mixed integer problems as a Pydantic model. References Q. Zhang and H. Li, "MOEA/D: A Multiobjective Evolutionary Algorithm Based on Decomposition," IEEE Transactions on Evolutionary Computation, vol. 11, no. 6, pp. 712-731, Dec. 2007, doi: 10.1109/TEVC.2007.892759. Returns: | Name | Type | Description | | ------------ | ------------ | ------------------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default MOEA/D mixed integer options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def moead_mixed_integer_options() -> EMOOptions: """Get default MOEA/D options for mixed integer problems as a Pydantic model. References: Q. Zhang and H. Li, "MOEA/D: A Multiobjective Evolutionary Algorithm Based on Decomposition," IEEE Transactions on Evolutionary Computation, vol. 11, no. 6, pp. 712-731, Dec. 2007, doi: 10.1109/TEVC.2007.892759. Returns: EMOOptions: The default MOEA/D mixed integer options as a Pydantic model. """ return _mixed_integer(moead_options(), "MOEA/D_Mixed_Integer") ``` ### moead_options ``` moead_options() -> EMOOptions ``` Get default MOEA/D options as a Pydantic model. The variant of Section V of the paper: Tchebycheff aggregation, no external population, simulated binary crossover and polynomial mutation, and neighbourhood mating with every improved neighbour replaced. References Q. Zhang and H. Li, "MOEA/D: A Multiobjective Evolutionary Algorithm Based on Decomposition," IEEE Transactions on Evolutionary Computation, vol. 11, no. 6, pp. 712-731, Dec. 2007, doi: 10.1109/TEVC.2007.892759. Returns: | Name | Type | Description | | ------------ | ------------ | ----------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default MOEA/D options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def moead_options() -> EMOOptions: """Get default MOEA/D options as a Pydantic model. The variant of Section V of the paper: Tchebycheff aggregation, no external population, simulated binary crossover and polynomial mutation, and neighbourhood mating with every improved neighbour replaced. References: Q. Zhang and H. Li, "MOEA/D: A Multiobjective Evolutionary Algorithm Based on Decomposition," IEEE Transactions on Evolutionary Computation, vol. 11, no. 6, pp. 712-731, Dec. 2007, doi: 10.1109/TEVC.2007.892759. Returns: EMOOptions: The default MOEA/D options as a Pydantic model. """ return EMOOptions( preference=None, template=TemplateMOEADOptions( algorithm_name="MOEA/D", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=20, # The paper's "crossover rate is 1.00" is per pair, following Deb's NSGA-II code, # whose per-variable rate is 0.5. The template keeps one of the two children. pair_xover_probability=1.0, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, # 1/n ), selection=MOEADSelectorOptions( name="MOEADSelector", # The paper uses N = 100 weight vectors at two objectives and 300 at three (H = 23). # At three objectives the simplex lattice gives 91 vectors for 100 requested. reference_vector_options=ReferenceVectorOptions( adaptation_frequency=0, creation_type="simplex", vector_type="planar", lattice_resolution=None, number_of_vectors=100, ), neighbourhood_size=20, neighbourhood_probability=1.0, max_replacements=None, aggregation="tchebycheff", ), # The population is drawn uniformly at random; the template sets its size to the number # of weight vectors. generator=RandomGeneratorOptions( name="RandomGenerator", n_points=100, ), repair=ClipRepairOptions(), # The paper runs 250 generations. Each generation spends one evaluation per weight vector. termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### nsga2_options ``` nsga2_options() -> EMOOptions ``` Get default NSGA-II options as a Pydantic model. Deb, K., Pratap, A., Agarwal, S., & Meyarivan, T. A. M. T. (2002). A fast and elitist multiobjective genetic algorithm: NSGA-II. IEEE transactions on evolutionary computation, 6(2), 182-197. Returns: | Name | Type | Description | | ------------ | ------------ | ------------------------------------------------ | | `EMOOptions` | `EMOOptions` | The default NSGA-II options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def nsga2_options() -> EMOOptions: """Get default NSGA-II options as a Pydantic model. Reference: Deb, K., Pratap, A., Agarwal, S., & Meyarivan, T. A. M. T. (2002). A fast and elitist multiobjective genetic algorithm: NSGA-II. IEEE transactions on evolutionary computation, 6(2), 182-197. Returns: EMOOptions: The default NSGA-II options as a Pydantic model. """ return EMOOptions( preference=None, template=Template2Options( algorithm_name="NSGA-II", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=20, # Note that the operator defaults are different in Template2 # NSGA-II reports p_c = 0.9, which is per pair, not per variable. pair_xover_probability=0.9, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, ), selection=NSGA2SelectorOptions( name="NSGA2Selector", population_size=100, ), mate_selection=TournamentSelectionOptions( name="TournamentSelection", tournament_size=2, winner_size=100, ), generator=LHSGeneratorOptions( name="LHSGenerator", n_points=100, ), # Deb's NSGA-II reference code clamps offspring onto the variable bounds. Leaving this as # NoRepair lets an operator that can leave the box (or emit NaN) feed straight into the # evaluator, which the other real-coded templates here already guard against. repair=ClipRepairOptions(), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### nsga3_mixed_integer_options ``` nsga3_mixed_integer_options() -> EMOOptions ``` Get default NSGA3 options for mixed integer problems as a Pydantic model. References K. Deb and H. Jain, “An Evolutionary Many-Objective Optimization Algorithm Using Reference-Point-Based Nondominated Sorting Approach, Part I: Solving Problems With Box Constraints,” IEEE Transactions on Evolutionary Computation, vol. 18, no. 4, pp. 577-601, Aug. 2014. J. Hakanen, T. Chugh, K. Sindhya, Y. Jin, and K. Miettinen, “Connections of reference vectors and different types of preference information in interactive multiobjective evolutionary algorithms,” in 2016 IEEE Symposium Series on Computational Intelligence (SSCI), Athens, Greece: IEEE, Dec. 2016, pp. 1-8. Returns: | Name | Type | Description | | ------------ | ------------ | ----------------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default NSGA3 mixed integer options as a Pydantic model | Source code in `desdeo/emo/options/algorithms.py` ``` def nsga3_mixed_integer_options() -> EMOOptions: """Get default NSGA3 options for mixed integer problems as a Pydantic model. References: K. Deb and H. Jain, “An Evolutionary Many-Objective Optimization Algorithm Using Reference-Point-Based Nondominated Sorting Approach, Part I: Solving Problems With Box Constraints,” IEEE Transactions on Evolutionary Computation, vol. 18, no. 4, pp. 577-601, Aug. 2014. J. Hakanen, T. Chugh, K. Sindhya, Y. Jin, and K. Miettinen, “Connections of reference vectors and different types of preference information in interactive multiobjective evolutionary algorithms,” in 2016 IEEE Symposium Series on Computational Intelligence (SSCI), Athens, Greece: IEEE, Dec. 2016, pp. 1-8. Returns: EMOOptions: The default NSGA3 mixed integer options as a Pydantic model """ return EMOOptions( preference=None, template=Template1Options( algorithm_name="NSGA3_Mixed_Integer", crossover=UniformMixedIntegerCrossoverOptions(), mutation=MixedIntegerRandomMutationOptions(), selection=NSGA3SelectorOptions( name="NSGA3Selector", reference_vector_options=ReferenceVectorOptions( adaptation_frequency=0, creation_type="simplex", vector_type="planar", lattice_resolution=None, number_of_vectors=100, adaptation_distance=0.2, reference_point=None, preferred_solutions=None, non_preferred_solutions=None, preferred_ranges=None, ), ), generator=RandomMixedIntegerGeneratorOptions(n_points=100), repair=NoRepairOptions( name="NoRepair", ), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### nsga3_options ``` nsga3_options() -> EMOOptions ``` Get default NSGA-III options as a Pydantic model. References K. Deb and H. Jain, “An Evolutionary Many-Objective Optimization Algorithm Using Reference-Point-Based Nondominated Sorting Approach, Part I: Solving Problems With Box Constraints,” IEEE Transactions on Evolutionary Computation, vol. 18, no. 4, pp. 577-601, Aug. 2014. J. Hakanen, T. Chugh, K. Sindhya, Y. Jin, and K. Miettinen, “Connections of reference vectors and different types of preference information in interactive multiobjective evolutionary algorithms,” in 2016 IEEE Symposium Series on Computational Intelligence (SSCI), Athens, Greece: IEEE, Dec. 2016, pp. 1-8. Returns: | Name | Type | Description | | ------------ | ------------ | ------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default NSGA-III options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def nsga3_options() -> EMOOptions: """Get default NSGA-III options as a Pydantic model. References: K. Deb and H. Jain, “An Evolutionary Many-Objective Optimization Algorithm Using Reference-Point-Based Nondominated Sorting Approach, Part I: Solving Problems With Box Constraints,” IEEE Transactions on Evolutionary Computation, vol. 18, no. 4, pp. 577-601, Aug. 2014. J. Hakanen, T. Chugh, K. Sindhya, Y. Jin, and K. Miettinen, “Connections of reference vectors and different types of preference information in interactive multiobjective evolutionary algorithms,” in 2016 IEEE Symposium Series on Computational Intelligence (SSCI), Athens, Greece: IEEE, Dec. 2016, pp. 1-8. Returns: EMOOptions: The default NSGA-III options as a Pydantic model. """ return EMOOptions( preference=None, template=Template1Options( algorithm_name="NSGA3", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=30, # The paper's p_c = 1 is a per-pair probability; the per-variable rate is Deb # and Agrawal's 0.5. Collapsing the two would cross every variable, not half. pair_xover_probability=1.0, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, ), selection=NSGA3SelectorOptions( name="NSGA3Selector", reference_vector_options=ReferenceVectorOptions( adaptation_frequency=0, creation_type="simplex", vector_type="planar", lattice_resolution=None, number_of_vectors=100, adaptation_distance=0.2, reference_point=None, preferred_solutions=None, non_preferred_solutions=None, preferred_ranges=None, ), ), generator=LHSGeneratorOptions( name="LHSGenerator", n_points=100, ), repair=ClipRepairOptions(), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### rvea_mixed_integer_options ``` rvea_mixed_integer_options() -> EMOOptions ``` Get default RVEA options for mixed integer problems as a Pydantic model. References R. Cheng, Y. Jin, M. Olhofer and B. Sendhoff, "A Reference Vector Guided Evolutionary Algorithm for Many- Objective Optimization," in IEEE Transactions on Evolutionary Computation, vol. 20, no. 5, pp. 773-791, Oct. 2016, doi: 10.1109/TEVC.2016.2519378. J. Hakanen, T. Chugh, K. Sindhya, Y. Jin, and K. Miettinen, “Connections of reference vectors and different types of preference information in interactive multiobjective evolutionary algorithms,” in 2016 IEEE Symposium Series on Computational Intelligence (SSCI), Athens, Greece: IEEE, Dec. 2016, pp. 1-8. Returns: | Name | Type | Description | | ------------ | ------------ | ---------------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default RVEA mixed integer options as a Pydantic model | Source code in `desdeo/emo/options/algorithms.py` ``` def rvea_mixed_integer_options() -> EMOOptions: """Get default RVEA options for mixed integer problems as a Pydantic model. References: R. Cheng, Y. Jin, M. Olhofer and B. Sendhoff, "A Reference Vector Guided Evolutionary Algorithm for Many- Objective Optimization," in IEEE Transactions on Evolutionary Computation, vol. 20, no. 5, pp. 773-791, Oct. 2016, doi: 10.1109/TEVC.2016.2519378. J. Hakanen, T. Chugh, K. Sindhya, Y. Jin, and K. Miettinen, “Connections of reference vectors and different types of preference information in interactive multiobjective evolutionary algorithms,” in 2016 IEEE Symposium Series on Computational Intelligence (SSCI), Athens, Greece: IEEE, Dec. 2016, pp. 1-8. Returns: EMOOptions: The default RVEA mixed integer options as a Pydantic model """ return EMOOptions( preference=None, template=Template1Options( algorithm_name="RVEA_Mixed_Integer", crossover=UniformMixedIntegerCrossoverOptions(), mutation=MixedIntegerRandomMutationOptions(), selection=RVEASelectorOptions( name="RVEASelector", alpha=2, parameter_adaptation_strategy=ParameterAdaptationStrategy.GENERATION_BASED, reference_vector_options=ReferenceVectorOptions( adaptation_frequency=100, creation_type="simplex", vector_type="spherical", lattice_resolution=None, number_of_vectors=100, adaptation_distance=0.2, reference_point=None, preferred_solutions=None, non_preferred_solutions=None, preferred_ranges=None, ), ), generator=RandomMixedIntegerGeneratorOptions(n_points=100), repair=NoRepairOptions( name="NoRepair", ), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### rvea_options ``` rvea_options() -> EMOOptions ``` Get default Reference Vector Guided Evolutionary Algorithm (RVEA) options as a Pydantic model. References R. Cheng, Y. Jin, M. Olhofer and B. Sendhoff, "A Reference Vector Guided Evolutionary Algorithm for Many- Objective Optimization," in IEEE Transactions on Evolutionary Computation, vol. 20, no. 5, pp. 773-791, Oct. 2016, doi: 10.1109/TEVC.2016.2519378. J. Hakanen, T. Chugh, K. Sindhya, Y. Jin, and K. Miettinen, “Connections of reference vectors and different types of preference information in interactive multiobjective evolutionary algorithms,” in 2016 IEEE Symposium Series on Computational Intelligence (SSCI), Athens, Greece: IEEE, Dec. 2016, pp. 1-8. Returns: | Name | Type | Description | | ------------ | ------------ | --------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default RVEA options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def rvea_options() -> EMOOptions: """Get default Reference Vector Guided Evolutionary Algorithm (RVEA) options as a Pydantic model. References: R. Cheng, Y. Jin, M. Olhofer and B. Sendhoff, "A Reference Vector Guided Evolutionary Algorithm for Many- Objective Optimization," in IEEE Transactions on Evolutionary Computation, vol. 20, no. 5, pp. 773-791, Oct. 2016, doi: 10.1109/TEVC.2016.2519378. J. Hakanen, T. Chugh, K. Sindhya, Y. Jin, and K. Miettinen, “Connections of reference vectors and different types of preference information in interactive multiobjective evolutionary algorithms,” in 2016 IEEE Symposium Series on Computational Intelligence (SSCI), Athens, Greece: IEEE, Dec. 2016, pp. 1-8. Returns: EMOOptions: The default RVEA options as a Pydantic model. """ return EMOOptions( preference=None, template=Template1Options( algorithm_name="RVEA", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=30, # The paper's p_c = 1 is a per-pair probability; the per-variable rate is Deb and # Agrawal's 0.5. Collapsing the two would cross every variable instead of half. pair_xover_probability=1.0, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, ), selection=RVEASelectorOptions( name="RVEASelector", alpha=2, parameter_adaptation_strategy=ParameterAdaptationStrategy.GENERATION_BASED, reference_vector_options=ReferenceVectorOptions( adaptation_frequency=100, creation_type="simplex", vector_type="spherical", lattice_resolution=None, number_of_vectors=100, adaptation_distance=0.2, reference_point=None, preferred_solutions=None, non_preferred_solutions=None, preferred_ranges=None, ), ), generator=LHSGeneratorOptions( name="LHSGenerator", n_points=100, ), repair=ClipRepairOptions(), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### sms_emoa_mixed_integer_options ``` sms_emoa_mixed_integer_options() -> EMOOptions ``` Get default SMS-EMOA options for mixed integer problems as a Pydantic model. References Beume, N., Naujoks, B., & Emmerich, M. (2007). SMS-EMOA: Multiobjective selection based on dominated hypervolume. European Journal of Operational Research, 181(3), 1653-1669. Returns: | Name | Type | Description | | ------------ | ------------ | --------------------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default SMS-EMOA mixed integer options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def sms_emoa_mixed_integer_options() -> EMOOptions: """Get default SMS-EMOA options for mixed integer problems as a Pydantic model. References: Beume, N., Naujoks, B., & Emmerich, M. (2007). SMS-EMOA: Multiobjective selection based on dominated hypervolume. European Journal of Operational Research, 181(3), 1653-1669. Returns: EMOOptions: The default SMS-EMOA mixed integer options as a Pydantic model. """ return EMOOptions( preference=None, template=Template3Options( algorithm_name="SMS-EMOA_Mixed_Integer", crossover=UniformMixedIntegerCrossoverOptions(), mutation=MixedIntegerRandomMutationOptions(), selection=SMSEMOASelectorOptions(), generator=RandomMixedIntegerGeneratorOptions(n_points=100), repair=NoRepairOptions( name="NoRepair", ), termination=MaxEvaluationsTerminatorOptions( name="MaxEvaluationsTerminator", max_evaluations=1000, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### sms_emoa_options ``` sms_emoa_options() -> EMOOptions ``` Get default SMS-EMOA options as a Pydantic model. References Beume, N., Naujoks, B., & Emmerich, M. (2007). SMS-EMOA: Multiobjective selection based on dominated hypervolume. European Journal of Operational Research, 181(3), 1653-1669. Returns: | Name | Type | Description | | ------------ | ------------ | ------------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default SMS-EMOA options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def sms_emoa_options() -> EMOOptions: """Get default SMS-EMOA options as a Pydantic model. References: Beume, N., Naujoks, B., & Emmerich, M. (2007). SMS-EMOA: Multiobjective selection based on dominated hypervolume. European Journal of Operational Research, 181(3), 1653-1669. Returns: EMOOptions: The default SMS-EMOA options as a Pydantic model. """ return EMOOptions( preference=None, template=Template3Options( algorithm_name="SMS-EMOA", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=30, pair_xover_probability=1.0, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, ), selection=SMSEMOASelectorOptions(), generator=LHSGeneratorOptions( name="LHSGenerator", n_points=100, ), repair=ClipRepairOptions(), termination=MaxEvaluationsTerminatorOptions( name="MaxEvaluationsTerminator", max_evaluations=1000, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### spea2_mixed_integer_options ``` spea2_mixed_integer_options() -> EMOOptions ``` Get default SPEA2 options for mixed integer problems as a Pydantic model. References E. Zitzler, M. Laumanns and L. Thiele, "SPEA2: Improving the Strength Pareto Evolutionary Algorithm," TIK-Report 103, Computer Engineering and Networks Laboratory (TIK), ETH Zurich, May 2001, doi: 10.3929/ethz-a-004284029. Returns: | Name | Type | Description | | ------------ | ------------ | ------------------------------------------------------------ | | `EMOOptions` | `EMOOptions` | The default SPEA2 mixed integer options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def spea2_mixed_integer_options() -> EMOOptions: """Get default SPEA2 options for mixed integer problems as a Pydantic model. References: E. Zitzler, M. Laumanns and L. Thiele, "SPEA2: Improving the Strength Pareto Evolutionary Algorithm," TIK-Report 103, Computer Engineering and Networks Laboratory (TIK), ETH Zurich, May 2001, doi: 10.3929/ethz-a-004284029. Returns: EMOOptions: The default SPEA2 mixed integer options as a Pydantic model. """ return _mixed_integer(spea2_options(), "SPEA2_Mixed_Integer") ``` ### spea2_options ``` spea2_options() -> EMOOptions ``` Get default SPEA2 options as a Pydantic model. The archive is the selected population, of size `population_size`, and the mating tournament fills a population of `winner_size` from it. The paper's continuous experiments set both to 100 and use SBX with eta = 20 and polynomial mutation; it does not state their rates, so the values here are the ones DESDEO uses for NSGA-II and IBEA. References E. Zitzler, M. Laumanns and L. Thiele, "SPEA2: Improving the Strength Pareto Evolutionary Algorithm," TIK-Report 103, Computer Engineering and Networks Laboratory (TIK), ETH Zurich, May 2001, doi: 10.3929/ethz-a-004284029. Returns: | Name | Type | Description | | ------------ | ------------ | ---------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default SPEA2 options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def spea2_options() -> EMOOptions: """Get default SPEA2 options as a Pydantic model. The archive is the selected population, of size `population_size`, and the mating tournament fills a population of `winner_size` from it. The paper's continuous experiments set both to 100 and use SBX with eta = 20 and polynomial mutation; it does not state their rates, so the values here are the ones DESDEO uses for NSGA-II and IBEA. References: E. Zitzler, M. Laumanns and L. Thiele, "SPEA2: Improving the Strength Pareto Evolutionary Algorithm," TIK-Report 103, Computer Engineering and Networks Laboratory (TIK), ETH Zurich, May 2001, doi: 10.3929/ethz-a-004284029. Returns: EMOOptions: The default SPEA2 options as a Pydantic model. """ return EMOOptions( preference=None, template=Template2Options( algorithm_name="SPEA2", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=20, pair_xover_probability=1.0, xover_probability=0.5, uniform_xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, ), selection=SPEA2SelectorOptions( name="SPEA2Selector", population_size=100, # the archive size, N-bar ), # Step 5: binary tournament with replacement on the archive fills the mating pool of N. mate_selection=TournamentSelectionOptions( name="TournamentSelection", tournament_size=2, winner_size=100, ), generator=LHSGeneratorOptions( name="LHSGenerator", n_points=100, ), repair=ClipRepairOptions(), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=100, ), use_archive=True, verbosity=2, seed=42, ), ) ``` ### xlemoo_options ``` xlemoo_options() -> EMOOptions ``` Get default XLEMOO options as a Pydantic model. XLEMOO alternates between Darwinian and Learning modes. Default cycle is 20 Darwinian iterations followed by 1 Learning iteration. The learning mode trains a SkopeRules classifier on the H/L split of past solutions and instantiates new candidates from the extracted rules. References Misitano, G. (2024). Exploring the explainable aspects and performance of a learnable evolutionary multiobjective optimization method. ACM Transactions on Evolutionary Learning and Optimization, 4(1), 1-39. Returns: | Name | Type | Description | | ------------ | ------------ | ----------------------------------------------- | | `EMOOptions` | `EMOOptions` | The default XLEMOO options as a Pydantic model. | Source code in `desdeo/emo/options/algorithms.py` ``` def xlemoo_options() -> EMOOptions: """Get default XLEMOO options as a Pydantic model. XLEMOO alternates between Darwinian and Learning modes. Default cycle is 20 Darwinian iterations followed by 1 Learning iteration. The learning mode trains a SkopeRules classifier on the H/L split of past solutions and instantiates new candidates from the extracted rules. References: Misitano, G. (2024). Exploring the explainable aspects and performance of a learnable evolutionary multiobjective optimization method. ACM Transactions on Evolutionary Learning and Optimization, 4(1), 1-39. Returns: EMOOptions: The default XLEMOO options as a Pydantic model. """ return EMOOptions( preference=None, template=TemplateXLEMOOOptions( algorithm_name="XLEMOO", crossover=SimulatedBinaryCrossoverOptions( name="SimulatedBinaryCrossover", xover_distribution=30, pair_xover_probability=1.0, xover_probability=0.5, ), mutation=BoundedPolynomialMutationOptions( name="BoundedPolynomialMutation", distribution_index=20, mutation_probability=None, ), selection=ElitistSelectionOptions( name="ElitistSelection", winner_size=50, target_column="asf", ), generator=LHSGeneratorOptions( name="LHSGenerator", n_points=50, ), repair=NoRepairOptions( name="NoRepair", ), termination=MaxGenerationsTerminatorOptions( name="MaxGenerationsTerminator", max_generations=200, ), n_darwin_per_cycle=20, n_learning_per_cycle=1, h_split=0.2, l_split=0.2, instantiation_factor=10.0, use_archive=True, verbosity=2, seed=42, ), ) ``` ## Templates JSON Schema for template options. ### XLEMOO_SCALARIZATIONS ``` XLEMOO_SCALARIZATIONS: dict[ str, Callable[..., tuple[Problem, str]] ] = { "asf_nondiff": add_asf_nondiff, "asf_diff": add_asf_diff, "stom_nondiff": add_stom_sf_nondiff, "stom_diff": add_stom_sf_diff, "guess_nondiff": add_guess_sf_nondiff, "guess_diff": add_guess_sf_diff, } ``` Reference-point scalarizations selectable from XLEMOO. Each callable must accept `(problem, symbol, reference_point)` and return `(problem, target_symbol)`. ### BaseTemplateOptions Bases: `BaseModel` Base class for template options. Source code in `desdeo/emo/options/templates.py` ``` class BaseTemplateOptions(BaseModel): """Base class for template options.""" model_config = {"use_attribute_docstrings": True} crossover: CrossoverOptions """The crossover operator options.""" mutation: MutationOptions """The mutation operator options.""" selection: SelectorOptions """The selection operator options.""" termination: TerminatorOptions """The termination operator options.""" generator: GeneratorOptions """The population generator options.""" repair: RepairOptions = Field(default=NoRepairOptions()) """The repair operator options.""" use_archive: bool = Field(default=True) """Whether to use an archive.""" seed: int = Field(default=0) """The seed for random number generation.""" verbosity: int = Field(default=2) """The verbosity level of the operators.""" algorithm_name: str """The unique name of the algorithm.""" ``` #### algorithm_name ``` algorithm_name: str ``` The unique name of the algorithm. #### crossover ``` crossover: CrossoverOptions ``` The crossover operator options. #### generator ``` generator: GeneratorOptions ``` The population generator options. #### mutation ``` mutation: MutationOptions ``` The mutation operator options. #### repair ``` repair: RepairOptions = Field(default=NoRepairOptions()) ``` The repair operator options. #### seed ``` seed: int = Field(default=0) ``` The seed for random number generation. #### selection ``` selection: SelectorOptions ``` The selection operator options. #### termination ``` termination: TerminatorOptions ``` The termination operator options. #### use_archive ``` use_archive: bool = Field(default=True) ``` Whether to use an archive. #### verbosity ``` verbosity: int = Field(default=2) ``` The verbosity level of the operators. ### ConstructorExtras Extra information returned by the emo_constructor. Source code in `desdeo/emo/options/templates.py` ``` @dataclass class ConstructorExtras: """Extra information returned by the emo_constructor.""" problem: Problem """New problem generated by the constructor (e.g. to handle preferences via IOPIS). If no new problem is generated, the original problem is returned.""" publisher: Publisher """The publisher associated with the current solver.""" archive: NonDominatedArchive | None """The archive associated with the current solver, if any.""" learning_operator: LearningModeOperator | None = None """The XLEMOO learning-mode operator, if the template is XLEMOO. ``None`` otherwise.""" ``` #### archive ``` archive: NonDominatedArchive | None ``` The archive associated with the current solver, if any. #### learning_operator ``` learning_operator: LearningModeOperator | None = None ``` The XLEMOO learning-mode operator, if the template is XLEMOO. `None` otherwise. #### problem ``` problem: Problem ``` New problem generated by the constructor (e.g. to handle preferences via IOPIS). If no new problem is generated, the original problem is returned. #### publisher ``` publisher: Publisher ``` The publisher associated with the current solver. ### DesirableRangesOptions Bases: `BaseModel` Options for providing desirable ranges for an EA. Source code in `desdeo/emo/options/templates.py` ``` class DesirableRangesOptions(BaseModel): """Options for providing desirable ranges for an EA.""" name: Literal["preferred_ranges"] = Field( default="preferred_ranges", frozen=True, description="The name of the preferred ranges option." ) """The name of the preferred ranges option.""" aspiration_levels: dict[str, float] = Field( description="The aspiration levels as a dictionary with objective function symbols as the keys." ) """The aspiration levels as a dictionary with objective function symbols as the keys.""" reservation_levels: dict[str, float] = Field( description="The reservation levels as a dictionary with objective function symbols as the keys." ) """The reservation levels as a dictionary with objective function symbols as the keys.""" method: Literal["Hakanen", "DF transformation", "Modified WASF-GA"] = Field( default="Hakanen", description="The method for handling the desirable ranges." ) """The method for handling the desirable ranges. "Modified WASF-GA" hands the levels to a `ModifiedWASFGASelector` as its aspiration and reservation points.""" desirability_levels: tuple[float, float] = Field( default=(0.9, 0.1), description=( "The desirability levels as a tuple (high, low). Used if method is DF transformation." " If None, default levels (0.9, 0.1) are used." ), ) ``` #### aspiration_levels ``` aspiration_levels: dict[str, float] = Field( description="The aspiration levels as a dictionary with objective function symbols as the keys." ) ``` The aspiration levels as a dictionary with objective function symbols as the keys. #### method ``` method: Literal[ "Hakanen", "DF transformation", "Modified WASF-GA" ] = Field( default="Hakanen", description="The method for handling the desirable ranges.", ) ``` The method for handling the desirable ranges. "Modified WASF-GA" hands the levels to a `ModifiedWASFGASelector` as its aspiration and reservation points. #### name ``` name: Literal["preferred_ranges"] = Field( default="preferred_ranges", frozen=True, description="The name of the preferred ranges option.", ) ``` The name of the preferred ranges option. #### reservation_levels ``` reservation_levels: dict[str, float] = Field( description="The reservation levels as a dictionary with objective function symbols as the keys." ) ``` The reservation levels as a dictionary with objective function symbols as the keys. ### EMOOptions Bases: `BaseModel` Options for configuring the EMO algorithm. Source code in `desdeo/emo/options/templates.py` ``` class EMOOptions(BaseModel): """Options for configuring the EMO algorithm.""" model_config = {"use_attribute_docstrings": True} preference: PreferenceOptions | None """The preference information for the EMO algorithm.""" template: TemplateOptions """The template options for the EMO algorithm.""" ``` #### preference ``` preference: PreferenceOptions | None ``` The preference information for the EMO algorithm. #### template ``` template: TemplateOptions ``` The template options for the EMO algorithm. ### InvalidTemplateError Bases: `Exception` Exception raised for invalid template configurations. Source code in `desdeo/emo/options/templates.py` ``` class InvalidTemplateError(Exception): """Exception raised for invalid template configurations.""" ``` ### NonPreferredSolutionsOptions Bases: `BaseModel` Options for providing non-preferred solutions for an EA. Source code in `desdeo/emo/options/templates.py` ``` class NonPreferredSolutionsOptions(BaseModel): """Options for providing non-preferred solutions for an EA.""" name: Literal["non_preferred_solutions"] = Field( default="non_preferred_solutions", frozen=True, description="The name of the non-preferred solutions option." ) """The name of the non-preferred solutions option.""" preference: dict[str, list[float]] = Field( description="The non-preferred solutions as a dictionary with objective function symbols as the keys." ) """The non-preferred solutions as a dictionary with objective function symbols as the keys.""" method: Literal["Hakanen"] = Field( default="Hakanen", description="The method for handling the non-preferred solutions." ) """The method for handling the non-preferred solutions.""" ``` #### method ``` method: Literal["Hakanen"] = Field( default="Hakanen", description="The method for handling the non-preferred solutions.", ) ``` The method for handling the non-preferred solutions. #### name ``` name: Literal["non_preferred_solutions"] = Field( default="non_preferred_solutions", frozen=True, description="The name of the non-preferred solutions option.", ) ``` The name of the non-preferred solutions option. #### preference ``` preference: dict[str, list[float]] = Field( description="The non-preferred solutions as a dictionary with objective function symbols as the keys." ) ``` The non-preferred solutions as a dictionary with objective function symbols as the keys. ### PreferredSolutionsOptions Bases: `BaseModel` Options for providing preferred solutions for an EA. Source code in `desdeo/emo/options/templates.py` ``` class PreferredSolutionsOptions(BaseModel): """Options for providing preferred solutions for an EA.""" name: Literal["preferred_solutions"] = Field( default="preferred_solutions", frozen=True, description="The name of the preferred solutions option." ) """The name of the preferred solutions option.""" preference: dict[str, list[float]] = Field( description="The preferred solutions as a dictionary with objective function symbols as the keys." ) """The preferred solutions as a dictionary with objective function symbols as the keys.""" method: Literal["Hakanen"] = Field( default="Hakanen", description="The method for handling the preferred solutions." ) """The method for handling the preferred solutions.""" ``` #### method ``` method: Literal["Hakanen"] = Field( default="Hakanen", description="The method for handling the preferred solutions.", ) ``` The method for handling the preferred solutions. #### name ``` name: Literal["preferred_solutions"] = Field( default="preferred_solutions", frozen=True, description="The name of the preferred solutions option.", ) ``` The name of the preferred solutions option. #### preference ``` preference: dict[str, list[float]] = Field( description="The preferred solutions as a dictionary with objective function symbols as the keys." ) ``` The preferred solutions as a dictionary with objective function symbols as the keys. ### ReferencePointOptions Bases: `BaseModel` Options for providing a reference point for an EA. Source code in `desdeo/emo/options/templates.py` ``` class ReferencePointOptions(BaseModel): """Options for providing a reference point for an EA.""" name: Literal["reference_point"] = Field( default="reference_point", frozen=True, description="The name of the reference point option." ) """The name of the reference point option.""" preference: dict[str, float] = Field( description="The reference point as a dictionary with objective function symbols as the keys." ) """The reference point as a dictionary with objective function symbols as the keys.""" method: Literal["Hakanen", "IOPIS"] = Field( default="Hakanen", description="The method for handling the reference point." ) """The method for handling the reference point.""" ``` #### method ``` method: Literal["Hakanen", "IOPIS"] = Field( default="Hakanen", description="The method for handling the reference point.", ) ``` The method for handling the reference point. #### name ``` name: Literal["reference_point"] = Field( default="reference_point", frozen=True, description="The name of the reference point option.", ) ``` The name of the reference point option. #### preference ``` preference: dict[str, float] = Field( description="The reference point as a dictionary with objective function symbols as the keys." ) ``` The reference point as a dictionary with objective function symbols as the keys. ### Template1Options Bases: `BaseTemplateOptions` Options for template 1. Template 1 is used by methods such as NSGA-III and RVEA. See template1 for more details. Source code in `desdeo/emo/options/templates.py` ``` class Template1Options(BaseTemplateOptions): """Options for template 1. Template 1 is used by methods such as NSGA-III and RVEA. See [template1][desdeo.emo.methods.templates.template1] for more details. """ name: Literal["Template1"] = Field(default="Template1", frozen=True, description="The name of the template.") """The name of the template.""" ``` #### name ``` name: Literal["Template1"] = Field( default="Template1", frozen=True, description="The name of the template.", ) ``` The name of the template. ### Template2Options Bases: `BaseTemplateOptions` Options for template 2. Template 2 is used by methods such as IBEA. See template2 for more details. Source code in `desdeo/emo/options/templates.py` ``` class Template2Options(BaseTemplateOptions): """Options for template 2. Template 2 is used by methods such as IBEA. See [template2][desdeo.emo.methods.templates.template2] for more details. """ name: Literal["Template2"] = Field(default="Template2", frozen=True, description="The name of the template.") """The name of the template.""" mate_selection: ScalarSelectionOptions = Field(description="The mate selection operator options.") ``` #### name ``` name: Literal["Template2"] = Field( default="Template2", frozen=True, description="The name of the template.", ) ``` The name of the template. ### Template3Options Bases: `BaseTemplateOptions` Options for template 3. Template 3 is used by methods such as SMS-EMOA. See template3 for more details. Source code in `desdeo/emo/options/templates.py` ``` class Template3Options(BaseTemplateOptions): """Options for template 3. Template 3 is used by methods such as SMS-EMOA. See [template3][desdeo.emo.methods.templates.template3] for more details. """ name: Literal["Template3"] = Field(default="Template3", frozen=True, description="The name of the template.") """The name of the template.""" ``` #### name ``` name: Literal["Template3"] = Field( default="Template3", frozen=True, description="The name of the template.", ) ``` The name of the template. ### TemplateMOEADOptions Bases: `BaseTemplateOptions` Options for the MOEA/D template. The MOEA/D template makes and evaluates one offspring per subproblem, replacing solutions as it goes. See template_moead for details. The population size is the number of weight vectors, which the selector's reference vector options decide. A generator with an `n_points` field is built with that many points, whatever its own `n_points` says; the simplex lattice, for instance, turns 100 requested vectors into 91 at three objectives. Any other generator must supply one solution per weight vector. Source code in `desdeo/emo/options/templates.py` ``` class TemplateMOEADOptions(BaseTemplateOptions): """Options for the MOEA/D template. The MOEA/D template makes and evaluates one offspring per subproblem, replacing solutions as it goes. See [template_moead][desdeo.emo.methods.templates.template_moead] for details. The population size is the number of weight vectors, which the selector's reference vector options decide. A generator with an `n_points` field is built with that many points, whatever its own `n_points` says; the simplex lattice, for instance, turns 100 requested vectors into 91 at three objectives. Any other generator must supply one solution per weight vector. """ name: Literal["TemplateMOEAD"] = Field( default="TemplateMOEAD", frozen=True, description="The name of the template." ) """The name of the template.""" selection: MOEADSelectorOptions = Field( # type: ignore[assignment] description="The MOEA/D selector options." ) """The MOEA/D selector, which holds the weight vectors, the neighbourhoods and the replacement rule.""" ``` #### name ``` name: Literal["TemplateMOEAD"] = Field( default="TemplateMOEAD", frozen=True, description="The name of the template.", ) ``` The name of the template. #### selection ``` selection: MOEADSelectorOptions = Field( description="The MOEA/D selector options." ) ``` The MOEA/D selector, which holds the weight vectors, the neighbourhoods and the replacement rule. ### TemplateXLEMOOOptions Bases: `BaseTemplateOptions` Options for the XLEMOO template. The XLEMOO template alternates between Darwinian (standard EA) and Learning (rule extraction + instantiation) modes. See template_xlemoo for details. Source code in `desdeo/emo/options/templates.py` ``` class TemplateXLEMOOOptions(BaseTemplateOptions): """Options for the XLEMOO template. The XLEMOO template alternates between Darwinian (standard EA) and Learning (rule extraction + instantiation) modes. See [template_xlemoo][desdeo.emo.methods.templates.template_xlemoo] for details. """ name: Literal["TemplateXLEMOO"] = Field( default="TemplateXLEMOO", frozen=True, description="The name of the template." ) """The name of the template.""" selection: ScalarSelectionOptions = Field( # type: ignore[assignment] description="The scalar selection operator (typically ElitistSelectionOptions)." ) """The scalar selection operator. XLEMOO is an elitist single-objective method, so the selection step is a scalar (top-N by a target column) rather than a multiobjective one.""" n_darwin_per_cycle: int = Field(default=20, gt=0, description="Number of Darwinian iterations per cycle.") """Number of Darwinian iterations per cycle.""" n_learning_per_cycle: int = Field(default=1, ge=0, description="Number of Learning iterations per cycle.") """Number of Learning iterations per cycle. Set to 0 to disable Learning mode.""" h_split: float = Field(default=0.2, gt=0, le=0.5, description="Top fraction of unique individuals used as H-group.") """Top fraction of unique individuals used as H-group.""" l_split: float = Field( default=0.2, gt=0, le=0.5, description="Bottom fraction of unique individuals used as L-group." ) """Bottom fraction of unique individuals used as L-group.""" instantiation_factor: float = Field( default=10.0, gt=0, description="Multiplier on population_size deciding how many individuals to instantiate." ) """Multiplier on population_size deciding how many individuals to instantiate.""" scalarization: Literal["asf_nondiff", "asf_diff", "stom_nondiff", "stom_diff", "guess_nondiff", "guess_diff"] = ( Field( default="asf_nondiff", description="Reference-point scalarization function added to the problem when a preference is supplied.", ) ) """Reference-point scalarization function added to the problem when a preference is supplied. Must be one of the keys of `XLEMOO_SCALARIZATIONS`.""" ``` #### h_split ``` h_split: float = Field( default=0.2, gt=0, le=0.5, description="Top fraction of unique individuals used as H-group.", ) ``` Top fraction of unique individuals used as H-group. #### instantiation_factor ``` instantiation_factor: float = Field( default=10.0, gt=0, description="Multiplier on population_size deciding how many individuals to instantiate.", ) ``` Multiplier on population_size deciding how many individuals to instantiate. #### l_split ``` l_split: float = Field( default=0.2, gt=0, le=0.5, description="Bottom fraction of unique individuals used as L-group.", ) ``` Bottom fraction of unique individuals used as L-group. #### n_darwin_per_cycle ``` n_darwin_per_cycle: int = Field( default=20, gt=0, description="Number of Darwinian iterations per cycle.", ) ``` Number of Darwinian iterations per cycle. #### n_learning_per_cycle ``` n_learning_per_cycle: int = Field( default=1, ge=0, description="Number of Learning iterations per cycle.", ) ``` Number of Learning iterations per cycle. Set to 0 to disable Learning mode. #### name ``` name: Literal["TemplateXLEMOO"] = Field( default="TemplateXLEMOO", frozen=True, description="The name of the template.", ) ``` The name of the template. #### scalarization ``` scalarization: Literal[ "asf_nondiff", "asf_diff", "stom_nondiff", "stom_diff", "guess_nondiff", "guess_diff", ] = Field( default="asf_nondiff", description="Reference-point scalarization function added to the problem when a preference is supplied.", ) ``` Reference-point scalarization function added to the problem when a preference is supplied. Must be one of the keys of `XLEMOO_SCALARIZATIONS`. #### selection ``` selection: ScalarSelectionOptions = Field( description="The scalar selection operator (typically ElitistSelectionOptions)." ) ``` The scalar selection operator. XLEMOO is an elitist single-objective method, so the selection step is a scalar (top-N by a target column) rather than a multiobjective one. ### \_xlemoo_preference_handler ``` _xlemoo_preference_handler( preference: PreferenceOptions | None, problem: Problem, selection: ScalarSelectionOptions, scalarization: str, ) -> tuple[Problem, ScalarSelectionOptions] ``` Attach the chosen reference-point scalarization for XLEMOO and point the selector at it. XLEMOO ranks solutions by a single scalarization target. If the user supplies a reference point preference, the scalarization named by `scalarization` is added to the problem and the selector's `target_column` is set to the resulting symbol. If no preference is given, the selector's existing `target_column` is assumed to already match a scalarization function on the problem. Source code in `desdeo/emo/options/templates.py` ``` def _xlemoo_preference_handler( preference: PreferenceOptions | None, problem: Problem, selection: ScalarSelectionOptions, scalarization: str, ) -> tuple[Problem, ScalarSelectionOptions]: """Attach the chosen reference-point scalarization for XLEMOO and point the selector at it. XLEMOO ranks solutions by a single scalarization target. If the user supplies a reference point preference, the scalarization named by ``scalarization`` is added to the problem and the selector's ``target_column`` is set to the resulting symbol. If no preference is given, the selector's existing ``target_column`` is assumed to already match a scalarization function on the problem. """ if selection.name != "ElitistSelection": raise InvalidTemplateError("XLEMOO requires an ElitistSelectionOptions scalar selection operator.") if preference is None: return problem, selection if not isinstance(preference, ReferencePointOptions): raise InvalidTemplateError("XLEMOO supports only ReferencePointOptions preferences.") if scalarization not in XLEMOO_SCALARIZATIONS: raise InvalidTemplateError( f"Unknown XLEMOO scalarization {scalarization!r}. Available: {sorted(XLEMOO_SCALARIZATIONS)}." ) target_symbol = selection.target_column or scalarization new_problem, target_symbol = XLEMOO_SCALARIZATIONS[scalarization]( problem, symbol=target_symbol, reference_point=preference.preference ) selection.target_column = target_symbol return new_problem, selection ``` ### emo_constructor ``` emo_constructor( emo_options: EMOOptions, problem: Problem, external_check: Callable[[], bool] | None = None, ) -> tuple[Callable[[], EMOResult], ConstructorExtras] ``` Construct an evolutionary algorithm from the given options. Parameters: | Name | Type | Description | Default | | ---------------- | ---------------------- | ---------------------------------- | --------------------------------------------------------------------------------------------- | | `emo_options` | `EMOOptions` | The options for the EMO algorithm. | *required* | | `problem` | `Problem` | The optimization problem to solve. | *required* | | `external_check` | \`Callable\[[], bool\] | None\` | A callable that returns True if the algorithm should stop, False otherwise. By default, None. | Returns: | Type | Description | | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | `Callable[[], EMOResult]` | tuple\[Callable\[[], EMOResult\], ConstructorExtras\]: A tuple containing the template function | | `ConstructorExtras` | and extra information such as the (possibly modified) problem, publisher, and archive. Run the template | | `tuple[Callable[[], EMOResult], ConstructorExtras]` | function to execute the algorithm. | Raises: | Type | Description | | ---------------------- | ----------------------------------------- | | `InvalidTemplateError` | If the template configuration is invalid. | Source code in `desdeo/emo/options/templates.py` ``` def emo_constructor( emo_options: EMOOptions, problem: Problem, external_check: Callable[[], bool] | None = None ) -> tuple[Callable[[], EMOResult], ConstructorExtras]: """Construct an evolutionary algorithm from the given options. Args: emo_options (EMOOptions): The options for the EMO algorithm. problem (Problem): The optimization problem to solve. external_check (Callable[[], bool] | None): A callable that returns True if the algorithm should stop, False otherwise. By default, None. Returns: tuple[Callable[[], EMOResult], ConstructorExtras]: A tuple containing the template function and extra information such as the (possibly modified) problem, publisher, and archive. Run the template function to execute the algorithm. Raises: InvalidTemplateError: If the template configuration is invalid. """ publisher = Publisher() template = emo_options.template if template.name == "TemplateXLEMOO": problem_, selector_options = _xlemoo_preference_handler( preference=emo_options.preference, problem=problem, selection=template.selection, scalarization=template.scalarization, ) else: problem_, selector_options = preference_handler( preference=emo_options.preference, problem=problem, selection=template.selection ) evaluator = EMOEvaluator(problem=problem_, publisher=publisher, verbosity=template.verbosity) if template.name == "TemplateXLEMOO": selector = scalar_selector_constructor( options=selector_options, publisher=publisher, verbosity=template.verbosity, seed=template.seed, problem=problem_, ) else: selector = selection_constructor( problem=problem_, options=selector_options, publisher=publisher, verbosity=template.verbosity, seed=template.seed, ) generator_options = template.generator if template.name == "TemplateMOEAD" and "n_points" in type(generator_options).model_fields: # MOEA/D keeps exactly one solution per weight vector. generator_options = generator_options.model_copy(update={"n_points": selector.number_of_subproblems}) generator = generator_constructor( problem=problem_, options=generator_options, evaluator=evaluator, publisher=publisher, verbosity=template.verbosity, seed=template.seed, ) crossover = crossover_constructor( problem=problem_, options=template.crossover, publisher=publisher, verbosity=template.verbosity, seed=template.seed, ) mutation = mutation_constructor( problem=problem_, options=template.mutation, publisher=publisher, verbosity=template.verbosity, seed=template.seed, ) terminator = terminator_constructor( options=template.termination, publisher=publisher, external_check=external_check, ) repair = repair_constructor(options=template.repair, problem=problem_) components = { "evaluator": evaluator, "generator": generator, "crossover": crossover, "mutation": mutation, "selection": selector, "terminator": terminator, } if template.use_archive: archive = NonDominatedArchive( problem=problem_, publisher=publisher, ) components["archive"] = archive if template.name == "Template2": scalar_selector = scalar_selector_constructor( options=template.mate_selection, publisher=publisher, verbosity=template.verbosity, seed=template.seed, problem=problem_, ) components["mate_selection"] = scalar_selector learning_operator: LearningModeOperator | None = None if template.name == "TemplateXLEMOO": if not isinstance(selector, ElitistSelection): raise InvalidTemplateError("XLEMOO requires an ElitistSelection scalar selector.") learning_operator = LearningModeOperator( problem=problem_, selector=selector, publisher=publisher, verbosity=template.verbosity, h_split=template.h_split, l_split=template.l_split, instantiation_factor=template.instantiation_factor, seed=template.seed, ) components["learning_operator"] = learning_operator consistency = publisher.check_consistency() if not consistency[0]: raise InvalidTemplateError(f"Inconsistent template configuration. See details:\n {consistency[1]}") archive = components.pop("archive", None) template_funcs = { "Template1": template1, "Template2": template2, "TemplateXLEMOO": template_xlemoo, "Template3": template3, "TemplateMOEAD": template_moead, } if template.name == "TemplateXLEMOO": constructor_extras = ConstructorExtras( problem=problem_, publisher=publisher, archive=archive, learning_operator=learning_operator, ) return ( partial( template_xlemoo, **components, repair=repair, n_darwin_per_cycle=template.n_darwin_per_cycle, n_learning_per_cycle=template.n_learning_per_cycle, ), constructor_extras, ) constructor_extras = ConstructorExtras(problem=problem_, publisher=publisher, archive=archive) if template.name in ("Template3", "TemplateMOEAD"): components["seed"] = template.seed return (partial(template_funcs[template.name], **components, repair=repair), constructor_extras) ``` ### preference_handler ``` preference_handler( preference: PreferenceOptions | None, problem: Problem, selection: SelectorOptions, ) -> tuple[Problem, SelectorOptions] ``` Handle the preference options for the EMO algorithm. This function modifies the problem and selection operator based on the provided preference options. E.g., if the preference method is "Hakanen", the reference vector options of the selection operator are modified to include the preference information. If the preference method is "IOPIS" or "DF transformation", the problem is modified to include desirability functions or IOPIS functions. If it is "Modified WASF-GA", the aspiration and reservation levels become the two reference points of a copy of the `ModifiedWASFGASelector` options. Parameters: | Name | Type | Description | Default | | ------------ | ------------------- | ------------------------------- | ----------------------- | | `preference` | \`PreferenceOptions | None\` | The preference options. | | `problem` | `Problem` | The optimization problem. | *required* | | `selection` | `SelectorOptions` | The selection operator options. | *required* | Returns: | Type | Description | | --------------------------------- | ------------------------------------------------------------------------------------------------------- | | `tuple[Problem, SelectorOptions]` | tuple\[Problem, SelectorOptions\]: The (modified, if necessary) problem and selection operator options. | Raises: | Type | Description | | ---------------------- | ------------------------------------------------------------------------------ | | `InvalidTemplateError` | If the preference handling method is incompatible with the selection operator. | Source code in `desdeo/emo/options/templates.py` ``` def preference_handler( preference: PreferenceOptions | None, problem: Problem, selection: SelectorOptions ) -> tuple[Problem, SelectorOptions]: """Handle the preference options for the EMO algorithm. This function modifies the problem and selection operator based on the provided preference options. E.g., if the preference method is "Hakanen", the reference vector options of the selection operator are modified to include the preference information. If the preference method is "IOPIS" or "DF transformation", the problem is modified to include desirability functions or IOPIS functions. If it is "Modified WASF-GA", the aspiration and reservation levels become the two reference points of a copy of the `ModifiedWASFGASelector` options. Args: preference (PreferenceOptions | None): The preference options. problem (Problem): The optimization problem. selection (SelectorOptions): The selection operator options. Returns: tuple[Problem, SelectorOptions]: The (modified, if necessary) problem and selection operator options. Raises: InvalidTemplateError: If the preference handling method is incompatible with the selection operator. """ if preference is None: return problem, selection if preference.method == "Hakanen": if "reference_vector_options" not in type(selection).model_fields: raise InvalidTemplateError( "Preference handling with Hakanen method requires a selection operator with reference vectors." ) if selection.name == "IBEASelector": # Technically not needed due to check above, but for shutting up linters raise InvalidTemplateError("Preference handling with Hakanen method is not supported for IBEASelector.") if selection.reference_vector_options is None: reference_vector_options = ReferenceVectorOptions() # Use default reference vector options else: reference_vector_options = selection.reference_vector_options if isinstance(preference, DesirableRangesOptions): preference_value = { obj.symbol: [preference.aspiration_levels[obj.symbol], preference.reservation_levels[obj.symbol]] for obj in problem.objectives } else: preference_value = preference.preference setattr(reference_vector_options, preference.name, preference_value) selection.reference_vector_options = reference_vector_options return problem, selection if preference.method == "IOPIS": iopis_problem, _ = add_iopis_funcs( problem=problem, reference_point=preference.preference, ) return iopis_problem, selection if preference.method == "Modified WASF-GA": if not isinstance(preference, DesirableRangesOptions): raise InvalidTemplateError("The Modified WASF-GA method takes aspiration and reservation levels.") if selection.name != "ModifiedWASFGASelector": raise InvalidTemplateError("The Modified WASF-GA method needs the ModifiedWASFGASelector.") selection = selection.model_copy( update={ "aspiration_levels": dict(preference.aspiration_levels), "reservation_levels": dict(preference.reservation_levels), } ) return problem, selection if preference.method == "DF transformation": df_problem, _ = add_desirability_funcs( problem=problem, aspiration_levels=preference.aspiration_levels, reservation_levels=preference.reservation_levels, desirability_levels=dict.fromkeys(preference.aspiration_levels, preference.desirability_levels), desirability_func="MaoMao", ) return df_problem, selection raise InvalidTemplateError(f"Unknown preference handling method: {preference.method}") ``` ## Crossover Operators JSON Schema for crossover operator options. ### BlendAlphaCrossoverOptions Bases: `BaseModel` Options for Blend Alpha Crossover. Source code in `desdeo/emo/options/crossover.py` ``` class BlendAlphaCrossoverOptions(BaseModel): """Options for Blend Alpha Crossover.""" model_config = {"use_attribute_docstrings": True} name: Literal["BlendAlphaCrossover"] = Field( default="BlendAlphaCrossover", frozen=True, ) """The name of the crossover operator.""" alpha: float = Field(default=0.5, ge=0.0) """ Non-negative blending factor 'alpha' that controls the extent to which offspring may be sampled outside the interval defined by each pair of parent genes. alpha = 0 restricts children strictly within the parents range, larger alpha allows outliers. """ repeats: int = Field(default=2, ge=1) """Number of offspring to generate per parent pair.""" sample_each_component: bool = Field( default=True, ) """If True, a new random number is generated for each component of the offspring. If False, a single random number is generated for the entire offspring.""" ``` #### alpha ``` alpha: float = Field(default=0.5, ge=0.0) ``` Non-negative blending factor 'alpha' that controls the extent to which offspring may be sampled outside the interval defined by each pair of parent genes. alpha = 0 restricts children strictly within the parents range, larger alpha allows outliers. #### name ``` name: Literal["BlendAlphaCrossover"] = Field( default="BlendAlphaCrossover", frozen=True ) ``` The name of the crossover operator. #### repeats ``` repeats: int = Field(default=2, ge=1) ``` Number of offspring to generate per parent pair. #### sample_each_component ``` sample_each_component: bool = Field(default=True) ``` If True, a new random number is generated for each component of the offspring. If False, a single random number is generated for the entire offspring. ### BoundedExponentialCrossoverOptions Bases: `BaseModel` Options for Bounded Exponential Crossover. Source code in `desdeo/emo/options/crossover.py` ``` class BoundedExponentialCrossoverOptions(BaseModel): """Options for Bounded Exponential Crossover.""" name: Literal["BoundedExponentialCrossover"] = Field( default="BoundedExponentialCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" xover_probability: float = Field(default=1.0, ge=0.0, le=1.0, description="The crossover probability.") """The crossover probability.""" lambda_: float = Field(default=0.1, gt=0.0, description="Positive scale λ for the exponential distribution.") """Positive scale λ for the exponential distribution.""" uniform_xover_probability: float = Field( default=0.0, ge=0.0, le=1.0, description=( "Per-variable probability that the two offspring exchange which parent they descend from. " "0.0 keeps the operator's original behaviour, where each offspring keeps its own parent's " "identity in every variable." ), ) """Per-variable probability that the two offspring exchange which parent they descend from. Defaults to 0.0, the operator's original behaviour. The same parameter on `SimulatedBinaryCrossoverOptions` defaults to 0.5 and separates that operator's two arms by 10.9x in median regret, so this is worth varying; the default stays at 0.0 because BEX is parent centric by construction and the transfer has not been measured.""" ``` #### lambda\_ ``` lambda_: float = Field( default=0.1, gt=0.0, description="Positive scale λ for the exponential distribution.", ) ``` Positive scale λ for the exponential distribution. #### name ``` name: Literal["BoundedExponentialCrossover"] = Field( default="BoundedExponentialCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. #### uniform_xover_probability ``` uniform_xover_probability: float = Field( default=0.0, ge=0.0, le=1.0, description="Per-variable probability that the two offspring exchange which parent they descend from. 0.0 keeps the operator's original behaviour, where each offspring keeps its own parent's identity in every variable.", ) ``` Per-variable probability that the two offspring exchange which parent they descend from. Defaults to 0.0, the operator's original behaviour. The same parameter on `SimulatedBinaryCrossoverOptions` defaults to 0.5 and separates that operator's two arms by 10.9x in median regret, so this is worth varying; the default stays at 0.0 because BEX is parent centric by construction and the transfer has not been measured. #### xover_probability ``` xover_probability: float = Field( default=1.0, ge=0.0, le=1.0, description="The crossover probability.", ) ``` The crossover probability. ### CompositeCrossoverOptions Bases: `BaseModel` Options for Composite Crossover. Source code in `desdeo/emo/options/crossover.py` ``` class CompositeCrossoverOptions(BaseModel): """Options for Composite Crossover.""" name: Literal["CompositeCrossover"] = Field( default="CompositeCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" crossovers: list[CrossoverOptions] = Field( default_factory=list, description="List of crossover options to be used in the composite crossover.", ) """List of crossover options to be used in the composite crossover.""" ``` #### crossovers ``` crossovers: list[CrossoverOptions] = Field( default_factory=list, description="List of crossover options to be used in the composite crossover.", ) ``` List of crossover options to be used in the composite crossover. #### name ``` name: Literal["CompositeCrossover"] = Field( default="CompositeCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. ### DifferentialEvolutionCrossoverOptions Bases: `BaseModel` Options for Differential Evolution crossover (DE/rand/1/bin). Source code in `desdeo/emo/options/crossover.py` ``` class DifferentialEvolutionCrossoverOptions(BaseModel): """Options for Differential Evolution crossover (DE/rand/1/bin).""" name: Literal["DifferentialEvolutionCrossover"] = Field( default="DifferentialEvolutionCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" scaling_factor: float = Field(default=0.5, gt=0.0, description="The factor F applied to the difference vector.") """The factor `F` applied to the difference vector `x_r2 - x_r3`. Defaults to 0.5, the midpoint of the 0.4-1.0 range Storn and Price recommend.""" xover_probability: float = Field(default=0.9, ge=0.0, le=1.0, description="The binomial crossover rate CR.") """The binomial crossover rate `CR`: the per-component probability that the offspring takes the mutant's value rather than the target's. One component is always taken from the mutant regardless, so no offspring is a copy of its target even at 0.0.""" base_vector: Literal["random", "target"] = Field( default="random", description="The vector the scaled difference is added to." ) """The vector the scaled difference is added to. "random" draws it as a third donor (DE/rand/1); "target" uses the target itself, `x_i + F * (x_r2 - x_r3)`, as MOEA/D-DE does (Li and Zhang 2009). Defaults to "random".""" ``` #### base_vector ``` base_vector: Literal["random", "target"] = Field( default="random", description="The vector the scaled difference is added to.", ) ``` The vector the scaled difference is added to. "random" draws it as a third donor (DE/rand/1); "target" uses the target itself, `x_i + F * (x_r2 - x_r3)`, as MOEA/D-DE does (Li and Zhang 2009). Defaults to "random". #### name ``` name: Literal["DifferentialEvolutionCrossover"] = Field( default="DifferentialEvolutionCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. #### scaling_factor ``` scaling_factor: float = Field( default=0.5, gt=0.0, description="The factor F applied to the difference vector.", ) ``` The factor `F` applied to the difference vector `x_r2 - x_r3`. Defaults to 0.5, the midpoint of the 0.4-1.0 range Storn and Price recommend. #### xover_probability ``` xover_probability: float = Field( default=0.9, ge=0.0, le=1.0, description="The binomial crossover rate CR.", ) ``` The binomial crossover rate `CR`: the per-component probability that the offspring takes the mutant's value rather than the target's. One component is always taken from the mutant regardless, so no offspring is a copy of its target even at 0.0. ### LocalCrossoverOptions Bases: `BaseModel` Options for Local Crossover. Source code in `desdeo/emo/options/crossover.py` ``` class LocalCrossoverOptions(BaseModel): """Options for Local Crossover.""" name: Literal["LocalCrossover"] = Field( default="LocalCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" ``` #### name ``` name: Literal["LocalCrossover"] = Field( default="LocalCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. ### ParentCentricCrossoverOptions Bases: `BaseModel` Options for Parent-Centric Crossover (PCX). Source code in `desdeo/emo/options/crossover.py` ``` class ParentCentricCrossoverOptions(BaseModel): """Options for Parent-Centric Crossover (PCX).""" name: Literal["ParentCentricCrossover"] = Field( default="ParentCentricCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" sigma_zeta: float = Field( default=0.1, gt=0.0, description="Standard deviation along the centroid-to-parent direction." ) """Standard deviation of the displacement along the direction from the parental centroid to the index parent. Defaults to 0.1, the value used throughout Deb, Anand and Joshi (2002).""" sigma_eta: float = Field(default=0.1, gt=0.0, description="Standard deviation orthogonal to that direction.") """Standard deviation of the displacement orthogonal to the centroid-to-parent direction, in units of the mean perpendicular distance of the other parents. Defaults to 0.1.""" ``` #### name ``` name: Literal["ParentCentricCrossover"] = Field( default="ParentCentricCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. #### sigma_eta ``` sigma_eta: float = Field( default=0.1, gt=0.0, description="Standard deviation orthogonal to that direction.", ) ``` Standard deviation of the displacement orthogonal to the centroid-to-parent direction, in units of the mean perpendicular distance of the other parents. Defaults to 0.1. #### sigma_zeta ``` sigma_zeta: float = Field( default=0.1, gt=0.0, description="Standard deviation along the centroid-to-parent direction.", ) ``` Standard deviation of the displacement along the direction from the parental centroid to the index parent. Defaults to 0.1, the value used throughout Deb, Anand and Joshi (2002). ### SimulatedBinaryCrossoverOptions Bases: `BaseModel` Options for Simulated Binary Crossover (SBX). Source code in `desdeo/emo/options/crossover.py` ``` class SimulatedBinaryCrossoverOptions(BaseModel): """Options for Simulated Binary Crossover (SBX).""" name: Literal["SimulatedBinaryCrossover"] = Field( default="SimulatedBinaryCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" pair_xover_probability: float = Field( default=1.0, ge=0.0, le=1.0, description="Probability that a parent pair is recombined at all." ) """Probability that a parent pair is recombined at all, drawn once per pair. On failure the pair is copied to the offspring unchanged, with all of its decision variables kept together. This is the `p_c` reported in the literature: 1.0 in the RVEA and NSGA-III papers, 0.9 in NSGA-II.""" xover_probability: float = Field( default=0.5, ge=0.0, le=1.0, description="The per-variable SBX crossover probability." ) """The per-variable SBX crossover probability, drawn once per decision variable. Defaults to 0.5, following Deb and Agrawal (1995): "we choose to perform SBX in each variable with probability 0.5". This is a separate level from `pair_xover_probability`; the literature's `p_c` refers to the pair, not to the variable, and belongs in `pair_xover_probability`.""" xover_distribution: float = Field(default=30.0, gt=0.0, description="The SBX distribution index.") """The SBX distribution index.""" truncated: bool = Field( default=True, description=( "Whether to truncate the probability distribution to keep the offspring within the variable bounds." ), ) """Whether to truncate the probability distribution to keep the offspring within the variable bounds.""" uniform_xover_probability: float = Field( default=0.5, ge=0.0, le=1.0, description="The uniform crossover probability." ) """The uniform crossover probability. Only operates on variables that have already been selected for crossover by the xover_probability parameter.""" swap_uncrossed_variables: bool = Field( default=False, description=( "Whether a decision variable not selected for SBX is exchanged between the two offspring " "instead of inherited unchanged. Set only to reproduce jMetal (Java)." ), ) """Whether a decision variable not selected by `xover_probability` is exchanged between the two offspring instead of inherited unchanged. Defaults to False, which is what every implementation surveyed does except jMetal (Java), whose else-branch assigns `offspring1[i] = parent2[i]` and `offspring2[i] = parent1[i]`. That adds a genuine uniform-crossover component on top of SBX: at the standard per-variable rate of 0.5, half of the genome is swapped wholesale every time a pair recombines.""" ``` #### name ``` name: Literal["SimulatedBinaryCrossover"] = Field( default="SimulatedBinaryCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. #### pair_xover_probability ``` pair_xover_probability: float = Field( default=1.0, ge=0.0, le=1.0, description="Probability that a parent pair is recombined at all.", ) ``` Probability that a parent pair is recombined at all, drawn once per pair. On failure the pair is copied to the offspring unchanged, with all of its decision variables kept together. This is the `p_c` reported in the literature: 1.0 in the RVEA and NSGA-III papers, 0.9 in NSGA-II. #### swap_uncrossed_variables ``` swap_uncrossed_variables: bool = Field( default=False, description="Whether a decision variable not selected for SBX is exchanged between the two offspring instead of inherited unchanged. Set only to reproduce jMetal (Java).", ) ``` Whether a decision variable not selected by `xover_probability` is exchanged between the two offspring instead of inherited unchanged. Defaults to False, which is what every implementation surveyed does except jMetal (Java), whose else-branch assigns `offspring1[i] = parent2[i]` and `offspring2[i] = parent1[i]`. That adds a genuine uniform-crossover component on top of SBX: at the standard per-variable rate of 0.5, half of the genome is swapped wholesale every time a pair recombines. #### truncated ``` truncated: bool = Field( default=True, description="Whether to truncate the probability distribution to keep the offspring within the variable bounds.", ) ``` Whether to truncate the probability distribution to keep the offspring within the variable bounds. #### uniform_xover_probability ``` uniform_xover_probability: float = Field( default=0.5, ge=0.0, le=1.0, description="The uniform crossover probability.", ) ``` The uniform crossover probability. Only operates on variables that have already been selected for crossover by the xover_probability parameter. #### xover_distribution ``` xover_distribution: float = Field( default=30.0, gt=0.0, description="The SBX distribution index.", ) ``` The SBX distribution index. #### xover_probability ``` xover_probability: float = Field( default=0.5, ge=0.0, le=1.0, description="The per-variable SBX crossover probability.", ) ``` The per-variable SBX crossover probability, drawn once per decision variable. Defaults to 0.5, following Deb and Agrawal (1995): "we choose to perform SBX in each variable with probability 0.5". This is a separate level from `pair_xover_probability`; the literature's `p_c` refers to the pair, not to the variable, and belongs in `pair_xover_probability`. ### SingleArithmeticCrossoverOptions Bases: `BaseModel` Options for Single Arithmetic Crossover. Source code in `desdeo/emo/options/crossover.py` ``` class SingleArithmeticCrossoverOptions(BaseModel): """Options for Single Arithmetic Crossover.""" name: Literal["SingleArithmeticCrossover"] = Field( default="SingleArithmeticCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" xover_probability: float = Field(default=1.0, ge=0.0, le=1.0, description="The crossover probability.") """The crossover probability.""" ``` #### name ``` name: Literal["SingleArithmeticCrossover"] = Field( default="SingleArithmeticCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. #### xover_probability ``` xover_probability: float = Field( default=1.0, ge=0.0, le=1.0, description="The crossover probability.", ) ``` The crossover probability. ### SinglePointBinaryCrossoverOptions Bases: `BaseModel` Options for Single Point Binary Crossover. Source code in `desdeo/emo/options/crossover.py` ``` class SinglePointBinaryCrossoverOptions(BaseModel): """Options for Single Point Binary Crossover.""" name: Literal["SinglePointBinaryCrossover"] = Field( default="SinglePointBinaryCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" ``` #### name ``` name: Literal["SinglePointBinaryCrossover"] = Field( default="SinglePointBinaryCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. ### UniformCrossoverOptions Bases: `BaseModel` Options for Uniform Crossover. Source code in `desdeo/emo/options/crossover.py` ``` class UniformCrossoverOptions(BaseModel): """Options for Uniform Crossover.""" model_config = {"use_attribute_docstrings": True} name: Literal["UniformCrossover"] = Field(default="UniformCrossover", frozen=True) """The name of the crossover operator.""" pair_xover_probability: float = Field(default=1.0, ge=0.0, le=1.0) """Probability that a parent pair is recombined at all, drawn once per pair. A pair that fails is copied to the offspring unchanged, with every decision variable kept together.""" uniform_xover_probability: float = Field(default=0.5, ge=0.0, le=1.0) """Per-variable probability that the two parents' values for that variable are exchanged between the offspring. 0.5 is Syswerda's rate. Named to match the parameter of the same meaning on `SimulatedBinaryCrossoverOptions`, so the mixing component can be held equal across the two.""" ``` #### name ``` name: Literal["UniformCrossover"] = Field( default="UniformCrossover", frozen=True ) ``` The name of the crossover operator. #### pair_xover_probability ``` pair_xover_probability: float = Field( default=1.0, ge=0.0, le=1.0 ) ``` Probability that a parent pair is recombined at all, drawn once per pair. A pair that fails is copied to the offspring unchanged, with every decision variable kept together. #### uniform_xover_probability ``` uniform_xover_probability: float = Field( default=0.5, ge=0.0, le=1.0 ) ``` Per-variable probability that the two parents' values for that variable are exchanged between the offspring. 0.5 is Syswerda's rate. Named to match the parameter of the same meaning on `SimulatedBinaryCrossoverOptions`, so the mixing component can be held equal across the two. ### UniformIntegerCrossoverOptions Bases: `BaseModel` Options for Uniform Integer Crossover. Source code in `desdeo/emo/options/crossover.py` ``` class UniformIntegerCrossoverOptions(BaseModel): """Options for Uniform Integer Crossover.""" name: Literal["UniformIntegerCrossover"] = Field( default="UniformIntegerCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" ``` #### name ``` name: Literal["UniformIntegerCrossover"] = Field( default="UniformIntegerCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. ### UniformMixedIntegerCrossoverOptions Bases: `BaseModel` Options for Uniform Mixed Integer Crossover. Source code in `desdeo/emo/options/crossover.py` ``` class UniformMixedIntegerCrossoverOptions(BaseModel): """Options for Uniform Mixed Integer Crossover.""" name: Literal["UniformMixedIntegerCrossover"] = Field( default="UniformMixedIntegerCrossover", frozen=True, description="The name of the crossover operator." ) """The name of the crossover operator.""" ``` #### name ``` name: Literal["UniformMixedIntegerCrossover"] = Field( default="UniformMixedIntegerCrossover", frozen=True, description="The name of the crossover operator.", ) ``` The name of the crossover operator. ### crossover_constructor ``` crossover_constructor( problem: Problem, publisher: Publisher, seed: int, verbosity: int, options: CrossoverOptions, ) -> BaseCrossover ``` Construct a crossover operator. Parameters: | Name | Type | Description | Default | | ----------- | ------------------ | --------------------------------------- | ---------- | | `problem` | `Problem` | The optimization problem to solve. | *required* | | `publisher` | `Publisher` | The publisher for communication. | *required* | | `seed` | `int` | The random seed for reproducibility. | *required* | | `verbosity` | `int` | The verbosity level of the output. | *required* | | `options` | `CrossoverOptions` | The options for the crossover operator. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ----------------------------------- | | `BaseCrossover` | `BaseCrossover` | The constructed crossover operator. | Source code in `desdeo/emo/options/crossover.py` ``` def crossover_constructor( problem: Problem, publisher: Publisher, seed: int, verbosity: int, options: CrossoverOptions ) -> BaseCrossover: """Construct a crossover operator. Args: problem (Problem): The optimization problem to solve. publisher (Publisher): The publisher for communication. seed (int): The random seed for reproducibility. verbosity (int): The verbosity level of the output. options (CrossoverOptions): The options for the crossover operator. Returns: BaseCrossover: The constructed crossover operator. """ crossover_types = { "SimulatedBinaryCrossover": SimulatedBinaryCrossover, "SinglePointBinaryCrossover": SinglePointBinaryCrossover, "UniformCrossover": UniformCrossover, "UniformIntegerCrossover": UniformIntegerCrossover, "UniformMixedIntegerCrossover": UniformMixedIntegerCrossover, "BlendAlphaCrossover": BlendAlphaCrossover, "SingleArithmeticCrossover": SingleArithmeticCrossover, "LocalCrossover": LocalCrossover, "BoundedExponentialCrossover": BoundedExponentialCrossover, "DifferentialEvolutionCrossover": DifferentialEvolutionCrossover, "ParentCentricCrossover": ParentCentricCrossover, "CompositeCrossover": CompositeCrossover, } if options.name != "CompositeCrossover": options = options.model_dump() name = options.pop("name") return crossover_types[name](problem=problem, publisher=publisher, seed=seed, verbosity=verbosity, **options) sub_crossovers = [crossover_constructor(problem, publisher, seed, verbosity, c) for c in options.crossovers] return CompositeCrossover( problem=problem, publisher=publisher, verbosity=verbosity, operators=sub_crossovers, seed=seed ) ``` ## Generator Operators JSON Schema for generator options. ### ArchiveGeneratorOptions Bases: `BaseModel` Options for Archive generator. Source code in `desdeo/emo/options/generator.py` ``` class ArchiveGeneratorOptions(BaseModel): """Options for Archive generator.""" model_config = {"arbitrary_types_allowed": True, "use_attribute_docstrings": True} name: Literal["ArchiveGenerator"] = "ArchiveGenerator" """The name of the generator.""" solutions: pl.DataFrame """The initial solutions to populate the archive with.""" outputs: pl.DataFrame """The corresponding outputs of the initial solutions.""" ``` #### name ``` name: Literal['ArchiveGenerator'] = 'ArchiveGenerator' ``` The name of the generator. #### outputs ``` outputs: DataFrame ``` The corresponding outputs of the initial solutions. #### solutions ``` solutions: DataFrame ``` The initial solutions to populate the archive with. ### BaseGeneratorOptions Bases: `BaseModel` Options for all generators. Source code in `desdeo/emo/options/generator.py` ``` class BaseGeneratorOptions(BaseModel): """Options for all generators.""" n_points: int = Field(gt=0, description="The number of points to generate for the initial population.") """The number of points to generate for the initial population.""" seed: int | None = Field( default=None, description=( "The random seed for the generator. If None the seed from the template will be used. IMPORTANT:" " Only set this seed in case you want to use a different seed for the generator than the rest of the" "algorithm. Otherwise leave this alone!" ), ) ``` #### n_points ``` n_points: int = Field( gt=0, description="The number of points to generate for the initial population.", ) ``` The number of points to generate for the initial population. ### LHSGeneratorOptions Bases: `BaseGeneratorOptions` Options for Latin Hypercube Sampling (LHS) generator. Source code in `desdeo/emo/options/generator.py` ``` class LHSGeneratorOptions(BaseGeneratorOptions): """Options for Latin Hypercube Sampling (LHS) generator.""" name: Literal["LHSGenerator"] = Field(default="LHSGenerator", frozen=True, description="The name of the generator.") """The name of the generator.""" ``` #### name ``` name: Literal["LHSGenerator"] = Field( default="LHSGenerator", frozen=True, description="The name of the generator.", ) ``` The name of the generator. ### RandomBinaryGeneratorOptions Bases: `BaseGeneratorOptions` Options for Random Binary generator. Source code in `desdeo/emo/options/generator.py` ``` class RandomBinaryGeneratorOptions(BaseGeneratorOptions): """Options for Random Binary generator.""" name: Literal["RandomBinaryGenerator"] = Field( default="RandomBinaryGenerator", frozen=True, description="The name of the generator." ) """The name of the generator.""" ``` #### name ``` name: Literal["RandomBinaryGenerator"] = Field( default="RandomBinaryGenerator", frozen=True, description="The name of the generator.", ) ``` The name of the generator. ### RandomGeneratorOptions Bases: `BaseGeneratorOptions` Options for Random generator. Source code in `desdeo/emo/options/generator.py` ``` class RandomGeneratorOptions(BaseGeneratorOptions): """Options for Random generator.""" name: Literal["RandomGenerator"] = Field( default="RandomGenerator", frozen=True, description="The name of the generator." ) """The name of the generator.""" ``` #### name ``` name: Literal["RandomGenerator"] = Field( default="RandomGenerator", frozen=True, description="The name of the generator.", ) ``` The name of the generator. ### RandomIntegerGeneratorOptions Bases: `BaseGeneratorOptions` Options for Random Integer generator. Source code in `desdeo/emo/options/generator.py` ``` class RandomIntegerGeneratorOptions(BaseGeneratorOptions): """Options for Random Integer generator.""" name: Literal["RandomIntegerGenerator"] = Field( default="RandomIntegerGenerator", frozen=True, description="The name of the generator." ) """The name of the generator.""" ``` #### name ``` name: Literal["RandomIntegerGenerator"] = Field( default="RandomIntegerGenerator", frozen=True, description="The name of the generator.", ) ``` The name of the generator. ### RandomMixedIntegerGeneratorOptions Bases: `BaseGeneratorOptions` Options for Random Mixed Integer generator. Source code in `desdeo/emo/options/generator.py` ``` class RandomMixedIntegerGeneratorOptions(BaseGeneratorOptions): """Options for Random Mixed Integer generator.""" name: Literal["RandomMixedIntegerGenerator"] = Field( default="RandomMixedIntegerGenerator", frozen=True, description="The name of the generator." ) """The name of the generator.""" ``` #### name ``` name: Literal["RandomMixedIntegerGenerator"] = Field( default="RandomMixedIntegerGenerator", frozen=True, description="The name of the generator.", ) ``` The name of the generator. ### SeededHybridGeneratorOptions Bases: `BaseGeneratorOptions` Options for the seeded hybrid generator. Source code in `desdeo/emo/options/generator.py` ``` class SeededHybridGeneratorOptions(BaseGeneratorOptions): """Options for the seeded hybrid generator.""" name: Literal["SeededHybridGenerator"] = Field(default="SeededHybridGenerator", frozen=True) model_config = {"arbitrary_types_allowed": True, "use_attribute_docstrings": True} seed_solution: pl.DataFrame """A dataframe with a single row representing the solution seed. The columns must math the symbols of the variables in the problem being solved. """ perturb_fraction: float = Field(default=0.2, ge=0.0, le=1.0) """The desired fraction of perturbed vs random solutions in the generated population.""" sigma: float = Field(default=0.02, ge=0.0) """The relative perturbation scale with respect to variable ranges.""" flip_prob: float = Field(default=0.1, ge=0.0, le=1.0) """The flipping probability when perturbing binary variables.""" ``` #### flip_prob ``` flip_prob: float = Field(default=0.1, ge=0.0, le=1.0) ``` The flipping probability when perturbing binary variables. #### perturb_fraction ``` perturb_fraction: float = Field(default=0.2, ge=0.0, le=1.0) ``` The desired fraction of perturbed vs random solutions in the generated population. #### seed_solution ``` seed_solution: DataFrame ``` A dataframe with a single row representing the solution seed. The columns must math the symbols of the variables in the problem being solved. #### sigma ``` sigma: float = Field(default=0.02, ge=0.0) ``` The relative perturbation scale with respect to variable ranges. ### generator_constructor ``` generator_constructor( problem: Problem, options: GeneratorOptions, publisher: Publisher, verbosity: int, seed: int, evaluator: EMOEvaluator, ) -> BaseGenerator ``` Construct a generator based on the provided options. Parameters: | Name | Type | Description | Default | | ----------- | ------------------ | ---------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The optimization problem to solve. | *required* | | `options` | `GeneratorOptions` | The options for the generator. | *required* | | `publisher` | `Publisher` | The publisher for the generator. | *required* | | `verbosity` | `int` | The verbosity level for the generator. | *required* | | `seed` | `int` | The random seed for the generator. Only used if the seed in options is None. | *required* | | `evaluator` | `EMOEvaluator` | The evaluator to use for evaluating solutions. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | -------------------------- | | `BaseGenerator` | `BaseGenerator` | The constructed generator. | Source code in `desdeo/emo/options/generator.py` ``` def generator_constructor( problem: Problem, options: GeneratorOptions, publisher: Publisher, verbosity: int, seed: int, evaluator: EMOEvaluator, ) -> BaseGenerator: """Construct a generator based on the provided options. Args: problem (Problem): The optimization problem to solve. options (GeneratorOptions): The options for the generator. publisher (Publisher): The publisher for the generator. verbosity (int): The verbosity level for the generator. seed (int): The random seed for the generator. Only used if the seed in options is None. evaluator (EMOEvaluator): The evaluator to use for evaluating solutions. Returns: BaseGenerator: The constructed generator. """ generator_types = { "LHSGenerator": LHSGenerator, "RandomBinaryGenerator": RandomBinaryGenerator, "RandomGenerator": RandomGenerator, "RandomIntegerGenerator": RandomIntegerGenerator, "RandomMixedIntegerGenerator": RandomMixedIntegerGenerator, "ArchiveGenerator": ArchiveGenerator, "SeededHybridGenerator": SeededHybridGenerator, } options: dict = options.model_dump() name = options.pop("name") if options.get("seed") is None: options["seed"] = seed return generator_types[name](problem, **options, publisher=publisher, verbosity=verbosity, evaluator=evaluator) ``` ## Mutation Operators JSON Schema for mutation operator options. ### MutationOptions ``` MutationOptions = ( BoundedPolynomialMutationOptions | BinaryFlipMutationOptions | IntegerRandomMutationOptions | MixedIntegerRandomMutationOptions | MPTMutationOptions | NonUniformMutationOptions | SelfAdaptiveGaussianMutationOptions | PowerMutationOptions ) ``` All possible mutation operator options. ### BinaryFlipMutationOptions Bases: `BaseModel` Options for Binary Flip Mutation. Source code in `desdeo/emo/options/mutation.py` ``` class BinaryFlipMutationOptions(BaseModel): """Options for Binary Flip Mutation.""" name: Literal["BinaryFlipMutation"] = Field( default="BinaryFlipMutation", frozen=True, description="The name of the mutation operator." ) """The name of the mutation operator.""" mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description=( "The probability of mutation. Defaults to None, which sets the " "mutation probability to 1/." ), ) """ The probability of mutation. Defaults to None, which sets the mutation probability to 1/. """ ``` #### mutation_probability ``` mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description="The probability of mutation. Defaults to None, which sets the mutation probability to 1/.", ) ``` The probability of mutation. Defaults to None, which sets the mutation probability to 1/. #### name ``` name: Literal["BinaryFlipMutation"] = Field( default="BinaryFlipMutation", frozen=True, description="The name of the mutation operator.", ) ``` The name of the mutation operator. ### BoundedPolynomialMutationOptions Bases: `BaseModel` Options for Bounded Polynomial Mutation. Source code in `desdeo/emo/options/mutation.py` ``` class BoundedPolynomialMutationOptions(BaseModel): """Options for Bounded Polynomial Mutation.""" model_config = {"use_attribute_docstrings": True} name: Literal["BoundedPolynomialMutation"] = Field( default="BoundedPolynomialMutation", frozen=True, ) """The name of the mutation operator.""" mutation_probability: float | None = Field(default=None, ge=0.0, le=1.0) """ The probability of mutation. Defaults to None, which sets the mutation probability to 1/. """ distribution_index: float = Field(default=20.0, gt=0.0) """The distribution index.""" ``` #### distribution_index ``` distribution_index: float = Field(default=20.0, gt=0.0) ``` The distribution index. #### mutation_probability ``` mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0 ) ``` The probability of mutation. Defaults to None, which sets the mutation probability to 1/. #### name ``` name: Literal["BoundedPolynomialMutation"] = Field( default="BoundedPolynomialMutation", frozen=True ) ``` The name of the mutation operator. ### IntegerRandomMutationOptions Bases: `BaseModel` Options for Integer Random Mutation. Source code in `desdeo/emo/options/mutation.py` ``` class IntegerRandomMutationOptions(BaseModel): """Options for Integer Random Mutation.""" name: Literal["IntegerRandomMutation"] = Field( default="IntegerRandomMutation", frozen=True, description="The name of the mutation operator." ) """The name of the mutation operator.""" mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description=( "The probability of mutation. Defaults to None, which sets the " "mutation probability to 1/." ), ) """ The probability of mutation. Defaults to None, which sets the mutation probability to 1/. """ ``` #### mutation_probability ``` mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description="The probability of mutation. Defaults to None, which sets the mutation probability to 1/.", ) ``` The probability of mutation. Defaults to None, which sets the mutation probability to 1/. #### name ``` name: Literal["IntegerRandomMutation"] = Field( default="IntegerRandomMutation", frozen=True, description="The name of the mutation operator.", ) ``` The name of the mutation operator. ### MPTMutationOptions Bases: `BaseModel` Options for MPT Mutation. Source code in `desdeo/emo/options/mutation.py` ``` class MPTMutationOptions(BaseModel): """Options for MPT Mutation.""" name: Literal["MPTMutation"] = Field( default="MPTMutation", frozen=True, description="The name of the mutation operator." ) """The name of the mutation operator.""" mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description=( "The probability of mutation. Defaults to None, which sets the " "mutation probability to 1/." ), ) """ The probability of mutation. Defaults to None, which sets the mutation probability to 1/. """ mutation_exponent: float = Field( default=2.0, ge=0.0, description="Controls strength of small mutation (larger means smaller mutations)." ) """Controls strength of small mutation (larger means smaller mutations).""" ``` #### mutation_exponent ``` mutation_exponent: float = Field( default=2.0, ge=0.0, description="Controls strength of small mutation (larger means smaller mutations).", ) ``` Controls strength of small mutation (larger means smaller mutations). #### mutation_probability ``` mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description="The probability of mutation. Defaults to None, which sets the mutation probability to 1/.", ) ``` The probability of mutation. Defaults to None, which sets the mutation probability to 1/. #### name ``` name: Literal["MPTMutation"] = Field( default="MPTMutation", frozen=True, description="The name of the mutation operator.", ) ``` The name of the mutation operator. ### MixedIntegerRandomMutationOptions Bases: `BaseModel` Options for Mixed Integer Random Mutation. Source code in `desdeo/emo/options/mutation.py` ``` class MixedIntegerRandomMutationOptions(BaseModel): """Options for Mixed Integer Random Mutation.""" name: Literal["MixedIntegerRandomMutation"] = Field( default="MixedIntegerRandomMutation", frozen=True, description="The name of the mutation operator." ) """The name of the mutation operator.""" mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description=( "The probability of mutation. Defaults to None, which sets the " "mutation probability to 1/." ), ) """ The probability of mutation. Defaults to None, which sets the mutation probability to 1/. """ ``` #### mutation_probability ``` mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description="The probability of mutation. Defaults to None, which sets the mutation probability to 1/.", ) ``` The probability of mutation. Defaults to None, which sets the mutation probability to 1/. #### name ``` name: Literal["MixedIntegerRandomMutation"] = Field( default="MixedIntegerRandomMutation", frozen=True, description="The name of the mutation operator.", ) ``` The name of the mutation operator. ### NonUniformMutationOptions Bases: `BaseModel` Options for Non-Uniform Mutation. Source code in `desdeo/emo/options/mutation.py` ``` class NonUniformMutationOptions(BaseModel): """Options for Non-Uniform Mutation.""" name: Literal["NonUniformMutation"] = Field( default="NonUniformMutation", frozen=True, description="The name of the mutation operator." ) """The name of the mutation operator.""" mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description=( "The probability of mutation. Defaults to None, which sets the " "mutation probability to 1/." ), ) """ The probability of mutation. Defaults to None, which sets the mutation probability to 1/. """ max_generations: int | None = Field( default=None, gt=0, description=( "Maximum number of generations in the evolutionary run, used to scale mutation decay. " "Defaults to None, which follows the budget reported by the terminator. Prefer the default: " "a value that disagrees with the terminator makes the decay schedule finish too early or not at all." ), ) """ Maximum number of generations in the evolutionary run, used to scale mutation decay. Defaults to None, which follows the budget reported by the terminator. """ b: float = Field( default=5.0, ge=0.0, description=( "Non-uniform mutation decay parameter. Higher values cause" "faster reduction in mutation strength over generations." ), ) """Non-uniform mutation decay parameter. Higher values cause faster reduction in mutation strength over generations.""" ``` #### b ``` b: float = Field( default=5.0, ge=0.0, description="Non-uniform mutation decay parameter. Higher values causefaster reduction in mutation strength over generations.", ) ``` Non-uniform mutation decay parameter. Higher values cause faster reduction in mutation strength over generations. #### max_generations ``` max_generations: int | None = Field( default=None, gt=0, description="Maximum number of generations in the evolutionary run, used to scale mutation decay. Defaults to None, which follows the budget reported by the terminator. Prefer the default: a value that disagrees with the terminator makes the decay schedule finish too early or not at all.", ) ``` Maximum number of generations in the evolutionary run, used to scale mutation decay. Defaults to None, which follows the budget reported by the terminator. #### mutation_probability ``` mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description="The probability of mutation. Defaults to None, which sets the mutation probability to 1/.", ) ``` The probability of mutation. Defaults to None, which sets the mutation probability to 1/. #### name ``` name: Literal["NonUniformMutation"] = Field( default="NonUniformMutation", frozen=True, description="The name of the mutation operator.", ) ``` The name of the mutation operator. ### PowerMutationOptions Bases: `BaseModel` Options for Power Mutation. Source code in `desdeo/emo/options/mutation.py` ``` class PowerMutationOptions(BaseModel): """Options for Power Mutation.""" name: Literal["PowerMutation"] = Field( default="PowerMutation", frozen=True, description="The name of the mutation operator." ) """The name of the mutation operator.""" mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description=( "The probability of mutation. Defaults to None, which sets the " "mutation probability to 1/." ), ) """ The probability of mutation. Defaults to None, which sets the mutation probability to 1/. """ p: float = Field( default=1.5, ge=0.0, description="Power distribution parameter. Controls the perturbation magnitude." ) """Power distribution parameter. Controls the perturbation magnitude.""" ``` #### mutation_probability ``` mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description="The probability of mutation. Defaults to None, which sets the mutation probability to 1/.", ) ``` The probability of mutation. Defaults to None, which sets the mutation probability to 1/. #### name ``` name: Literal["PowerMutation"] = Field( default="PowerMutation", frozen=True, description="The name of the mutation operator.", ) ``` The name of the mutation operator. #### p ``` p: float = Field( default=1.5, ge=0.0, description="Power distribution parameter. Controls the perturbation magnitude.", ) ``` Power distribution parameter. Controls the perturbation magnitude. ### SelfAdaptiveGaussianMutationOptions Bases: `BaseModel` Options for Self-Adaptive Gaussian Mutation. Source code in `desdeo/emo/options/mutation.py` ``` class SelfAdaptiveGaussianMutationOptions(BaseModel): """Options for Self-Adaptive Gaussian Mutation.""" name: Literal["SelfAdaptiveGaussianMutation"] = Field( default="SelfAdaptiveGaussianMutation", frozen=True, description="The name of the mutation operator." ) """The name of the mutation operator.""" mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description=( "The probability of mutation. Defaults to None, which sets the " "mutation probability to 1/." ), ) """ The probability of mutation. Defaults to None, which sets the mutation probability to 1/. """ ``` #### mutation_probability ``` mutation_probability: float | None = Field( default=None, ge=0.0, le=1.0, description="The probability of mutation. Defaults to None, which sets the mutation probability to 1/.", ) ``` The probability of mutation. Defaults to None, which sets the mutation probability to 1/. #### name ``` name: Literal["SelfAdaptiveGaussianMutation"] = Field( default="SelfAdaptiveGaussianMutation", frozen=True, description="The name of the mutation operator.", ) ``` The name of the mutation operator. ### mutation_constructor ``` mutation_constructor( problem: Problem, publisher: Publisher, seed: int, verbosity: int, options: MutationOptions, ) -> BaseMutation ``` Construct a mutation operator. Parameters: | Name | Type | Description | Default | | ----------- | ----------------- | -------------------------------------- | ---------- | | `problem` | `Problem` | The optimization problem to solve. | *required* | | `publisher` | `Publisher` | The publisher for communication. | *required* | | `seed` | `int` | The random seed for reproducibility. | *required* | | `verbosity` | `int` | The verbosity level of the output. | *required* | | `options` | `MutationOptions` | The options for the mutation operator. | *required* | Returns: | Name | Type | Description | | --------------- | -------------- | ----------------------------------- | | `BaseCrossover` | `BaseMutation` | The constructed crossover operator. | Source code in `desdeo/emo/options/mutation.py` ``` def mutation_constructor( problem: Problem, publisher: Publisher, seed: int, verbosity: int, options: MutationOptions ) -> BaseMutation: """Construct a mutation operator. Args: problem (Problem): The optimization problem to solve. publisher (Publisher): The publisher for communication. seed (int): The random seed for reproducibility. verbosity (int): The verbosity level of the output. options (MutationOptions): The options for the mutation operator. Returns: BaseCrossover: The constructed crossover operator. """ mutation_types = { "BoundedPolynomialMutation": BoundedPolynomialMutation, "BinaryFlipMutation": BinaryFlipMutation, "IntegerRandomMutation": IntegerRandomMutation, "MixedIntegerRandomMutation": MixedIntegerRandomMutation, "MPTMutation": MPTMutation, "NonUniformMutation": NonUniformMutation, "SelfAdaptiveGaussianMutation": SelfAdaptiveGaussianMutation, "PowerMutation": PowerMutation, } options: dict = options.model_dump() name = options.pop("name") return mutation_types[name](problem=problem, publisher=publisher, seed=seed, verbosity=verbosity, **options) ``` ## Repair Functions JSON Schema for repair operator options. ### ClipRepairOptions Bases: `BaseModel` Options for Clip Repair. Source code in `desdeo/emo/options/repair.py` ``` class ClipRepairOptions(BaseModel): """Options for Clip Repair.""" model_config = ConfigDict(use_attribute_docstrings=True) name: Literal["ClipRepair"] = Field(default="ClipRepair") """Clip the solutions to be within the variable bounds.""" lower_bounds: dict[str, float] | None = None """Lower bounds for the decision variables. If none, the lower bounds from the problem will be used.""" upper_bounds: dict[str, float] | None = None """Upper bounds for the decision variables. If none, the upper bounds from the problem will be used.""" ``` #### lower_bounds ``` lower_bounds: dict[str, float] | None = None ``` Lower bounds for the decision variables. If none, the lower bounds from the problem will be used. #### name ``` name: Literal['ClipRepair'] = Field(default='ClipRepair') ``` Clip the solutions to be within the variable bounds. #### upper_bounds ``` upper_bounds: dict[str, float] | None = None ``` Upper bounds for the decision variables. If none, the upper bounds from the problem will be used. ### NoRepairOptions Bases: `BaseModel` Options for No Repair. Source code in `desdeo/emo/options/repair.py` ``` class NoRepairOptions(BaseModel): """Options for No Repair.""" model_config = ConfigDict(use_attribute_docstrings=True) name: Literal["NoRepair"] = Field(default="NoRepair") """Do not apply any repair to the solutions.""" ``` #### name ``` name: Literal['NoRepair'] = Field(default='NoRepair') ``` Do not apply any repair to the solutions. ### repair_constructor ``` repair_constructor( options: RepairOptions, problem: Problem ) -> Callable[[pl.DataFrame], pl.DataFrame] ``` Get the repair operator based on the provided options. Parameters: | Name | Type | Description | Default | | --------- | --------------- | ---------------------------------- | ---------- | | `options` | `RepairOptions` | The repair options. | *required* | | `problem` | `Problem` | The optimization problem to solve. | *required* | Returns: | Name | Type | Description | | ---------- | ---------------------------------- | ----------------------------- | | `callable` | `Callable[[DataFrame], DataFrame]` | The repair operator function. | Source code in `desdeo/emo/options/repair.py` ``` def repair_constructor(options: RepairOptions, problem: Problem) -> Callable[[pl.DataFrame], pl.DataFrame]: """Get the repair operator based on the provided options. Args: options (RepairOptions): The repair options. problem (Problem): The optimization problem to solve. Returns: callable: The repair operator function. """ if options.name == "NoRepair": return lambda x: x # No repair, return input as is if options.name == "ClipRepair": if options.lower_bounds is None: lower_bounds = {var.symbol: var.lowerbound for var in problem.get_flattened_variables()} else: lower_bounds = options.lower_bounds if options.upper_bounds is None: upper_bounds = {var.symbol: var.upperbound for var in problem.get_flattened_variables()} else: upper_bounds = options.upper_bounds return repair(lower_bounds=lower_bounds, upper_bounds=upper_bounds) raise ValueError(f"Unknown repair operator: {options.name}") ``` ## Scalar Selection Operators JSON Schema for scalar selector operator options. ### ElitistSelectionOptions Bases: `BaseModel` Options for elitist scalar selection (top `winner_size` by a target column). Source code in `desdeo/emo/options/scalar_selection.py` ``` class ElitistSelectionOptions(BaseModel): """Options for elitist scalar selection (top ``winner_size`` by a target column).""" name: Literal["ElitistSelection"] = Field( default="ElitistSelection", frozen=True, description="The name of the scalar selection operator." ) """The name of the scalar selection operator.""" winner_size: int = Field(gt=0, description="The number of individuals to keep after selection.") """The number of individuals to keep after selection.""" target_column: str = Field(description="Name of the output column to sort by (ascending, lower is better).") """Name of the output column to sort by (ascending, lower is better).""" ``` #### name ``` name: Literal["ElitistSelection"] = Field( default="ElitistSelection", frozen=True, description="The name of the scalar selection operator.", ) ``` The name of the scalar selection operator. #### target_column ``` target_column: str = Field( description="Name of the output column to sort by (ascending, lower is better)." ) ``` Name of the output column to sort by (ascending, lower is better). #### winner_size ``` winner_size: int = Field( gt=0, description="The number of individuals to keep after selection.", ) ``` The number of individuals to keep after selection. ### RouletteWheelSelectionOptions Bases: `TournamentSelectionOptions` Options for roulette wheel selection operator. Source code in `desdeo/emo/options/scalar_selection.py` ``` class RouletteWheelSelectionOptions(TournamentSelectionOptions): """Options for roulette wheel selection operator.""" name: Literal["RouletteWheelSelection"] = Field( default="RouletteWheelSelection", frozen=True, description="The name of the scalar selection operator." ) """The name of the scalar selection operator.""" comparison: Literal["fitness"] = Field( # type: ignore[assignment] default="fitness", description="A roulette wheel draws the winner in proportion to fitness, so it only compares by fitness.", ) """A roulette wheel draws the winner in proportion to fitness, so it only compares by fitness.""" ``` #### comparison ``` comparison: Literal["fitness"] = Field( default="fitness", description="A roulette wheel draws the winner in proportion to fitness, so it only compares by fitness.", ) ``` A roulette wheel draws the winner in proportion to fitness, so it only compares by fitness. #### name ``` name: Literal["RouletteWheelSelection"] = Field( default="RouletteWheelSelection", frozen=True, description="The name of the scalar selection operator.", ) ``` The name of the scalar selection operator. ### TournamentSelectionOptions Bases: `BaseModel` Options for tournament selection operator. Source code in `desdeo/emo/options/scalar_selection.py` ``` class TournamentSelectionOptions(BaseModel): """Options for tournament selection operator.""" name: Literal["TournamentSelection"] = Field( default="TournamentSelection", frozen=True, description="The name of the scalar selection operator." ) """The name of the scalar selection operator.""" tournament_size: int = Field( default=2, description="The number of individuals participating in the tournament.", ) """The number of individuals participating in the tournament.""" winner_size: int = Field( gt=1, description="The number of winners to select (equivalent to population size).", ) """The number of winners to select (equivalent to population size).""" comparison: Literal["fitness", "dominance"] = Field( default="fitness", description=( "How the members of a tournament are compared. 'fitness' picks the highest fitness the selector " "publishes. 'dominance' picks uniformly among the members no other member dominates, under " "constrained domination, and ignores the fitness." ), ) """How the members of a tournament are compared. 'fitness' picks the highest fitness the selector publishes. 'dominance' picks uniformly among the members no other member dominates, under constrained domination, and ignores the fitness.""" ``` #### comparison ``` comparison: Literal["fitness", "dominance"] = Field( default="fitness", description="How the members of a tournament are compared. 'fitness' picks the highest fitness the selector publishes. 'dominance' picks uniformly among the members no other member dominates, under constrained domination, and ignores the fitness.", ) ``` How the members of a tournament are compared. 'fitness' picks the highest fitness the selector publishes. 'dominance' picks uniformly among the members no other member dominates, under constrained domination, and ignores the fitness. #### name ``` name: Literal["TournamentSelection"] = Field( default="TournamentSelection", frozen=True, description="The name of the scalar selection operator.", ) ``` The name of the scalar selection operator. #### tournament_size ``` tournament_size: int = Field( default=2, description="The number of individuals participating in the tournament.", ) ``` The number of individuals participating in the tournament. #### winner_size ``` winner_size: int = Field( gt=1, description="The number of winners to select (equivalent to population size).", ) ``` The number of winners to select (equivalent to population size). ### scalar_selector_constructor ``` scalar_selector_constructor( options: ScalarSelectionOptions, seed: int, publisher: Publisher, verbosity: int, problem: Problem | None = None, ) -> BaseScalarSelector ``` Construct a scalar selector operator based on the provided options. Parameters: | Name | Type | Description | Default | | ----------- | ------------------------ | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `options` | `ScalarSelectionOptions` | The options of the operator. | *required* | | `seed` | `int` | The seed of the operator's random number generator. | *required* | | `publisher` | `Publisher` | The publisher the operator subscribes to. | *required* | | `verbosity` | `int` | The verbosity of the operator's messages. | *required* | | `problem` | \`Problem | None\` | The problem being solved. A tournament that compares by dominance reads its targets and constraints from it. Defaults to None. | Returns: | Name | Type | Description | | -------------------- | -------------------- | ------------- | | `BaseScalarSelector` | `BaseScalarSelector` | The operator. | Raises: | Type | Description | | ------------ | ---------------------------------------------------------------------------------------- | | `ValueError` | If the operator is unknown, or if a dominance tournament is asked for without a problem. | Source code in `desdeo/emo/options/scalar_selection.py` ``` def scalar_selector_constructor( options: ScalarSelectionOptions, seed: int, publisher: Publisher, verbosity: int, problem: Problem | None = None, ) -> BaseScalarSelector: """Construct a scalar selector operator based on the provided options. Args: options (ScalarSelectionOptions): The options of the operator. seed (int): The seed of the operator's random number generator. publisher (Publisher): The publisher the operator subscribes to. verbosity (int): The verbosity of the operator's messages. problem (Problem | None, optional): The problem being solved. A tournament that compares by dominance reads its targets and constraints from it. Defaults to None. Returns: BaseScalarSelector: The operator. Raises: ValueError: If the operator is unknown, or if a dominance tournament is asked for without a problem. """ if options.name == "TournamentSelection": if options.comparison == "dominance": if problem is None: raise ValueError("A tournament that compares by dominance needs the problem to read its targets.") return TournamentSelection( tournament_size=options.tournament_size, winner_size=options.winner_size, seed=seed, publisher=publisher, verbosity=verbosity, comparison="dominance", target_symbols=[f"{obj.symbol}_min" for obj in problem.objectives], constraint_symbols=[con.symbol for con in problem.constraints] if problem.constraints else None, ) return TournamentSelection( tournament_size=options.tournament_size, winner_size=options.winner_size, seed=seed, publisher=publisher, verbosity=verbosity, ) if options.name == "RouletteWheelSelection": return TournamentSelection( # It implements both (and more) winner_size=options.winner_size, seed=seed, stochastic=True, # Drawing the winner by fitness is what makes it a roulette wheel publisher=publisher, verbosity=verbosity, tournament_size=options.tournament_size, ) if options.name == "ElitistSelection": return ElitistSelection( winner_size=options.winner_size, target_column=options.target_column, publisher=publisher, verbosity=verbosity, ) raise ValueError(f"Unknown scalar selection operator: {options.name}") ``` ## Selection Operators JSON Schema for selection operator options. ### AGEMOEA2SelectorOptions Bases: `BaseModel` Options for AGE-MOEA-II environmental selection. Source code in `desdeo/emo/options/selection.py` ``` class AGEMOEA2SelectorOptions(BaseModel): """Options for AGE-MOEA-II environmental selection.""" model_config = ConfigDict(use_attribute_docstrings=True) name: Literal["AGEMOEA2Selector"] = Field( default="AGEMOEA2Selector", frozen=True, description="The name of the selection operator." ) """The name of the selection operator.""" population_size: int = Field(gt=0, description="The population size.") """The population size.""" ``` #### name ``` name: Literal["AGEMOEA2Selector"] = Field( default="AGEMOEA2Selector", frozen=True, description="The name of the selection operator.", ) ``` The name of the selection operator. #### population_size ``` population_size: int = Field( gt=0, description="The population size." ) ``` The population size. ### HypESelectorOptions Bases: `BaseModel` Options for HypE environmental selection. Source code in `desdeo/emo/options/selection.py` ``` class HypESelectorOptions(BaseModel): """Options for HypE environmental selection.""" model_config = ConfigDict(use_attribute_docstrings=True) name: Literal["HypESelector"] = Field( default="HypESelector", frozen=True, description="The name of the selection operator." ) """The name of the selection operator.""" population_size: int = Field(gt=0, description="The population size.") """The population size.""" n_samples: int = Field(default=10_000, gt=0, description="The number of Monte Carlo samples.") """The number of Monte Carlo samples M used to estimate the hypervolume fitness above `exact_max_objectives` objectives. Defaults to the paper's 10 000.""" exact_max_objectives: int = Field( default=3, ge=0, le=3, description="The most objectives for which the fitness is computed exactly." ) """The most objectives for which the hypervolume fitness is computed exactly rather than estimated. Defaults to 3, as the paper recommends.""" normalised_reference_point_component: float = Field( default=1.1, gt=1.0, description="The reference point in every normalized objective." ) """The reference point in every objective after normalizing parents and offspring to [0, 1]. The paper leaves the reference point to the user.""" ``` #### exact_max_objectives ``` exact_max_objectives: int = Field( default=3, ge=0, le=3, description="The most objectives for which the fitness is computed exactly.", ) ``` The most objectives for which the hypervolume fitness is computed exactly rather than estimated. Defaults to 3, as the paper recommends. #### n_samples ``` n_samples: int = Field( default=10000, gt=0, description="The number of Monte Carlo samples.", ) ``` The number of Monte Carlo samples M used to estimate the hypervolume fitness above `exact_max_objectives` objectives. Defaults to the paper's 10 000. #### name ``` name: Literal["HypESelector"] = Field( default="HypESelector", frozen=True, description="The name of the selection operator.", ) ``` The name of the selection operator. #### normalised_reference_point_component ``` normalised_reference_point_component: float = Field( default=1.1, gt=1.0, description="The reference point in every normalized objective.", ) ``` The reference point in every objective after normalizing parents and offspring to [0, 1]. The paper leaves the reference point to the user. #### population_size ``` population_size: int = Field( gt=0, description="The population size." ) ``` The population size. ### IBEASelectorOptions Bases: `BaseModel` Options for IBEA Selection. Source code in `desdeo/emo/options/selection.py` ``` class IBEASelectorOptions(BaseModel): """Options for IBEA Selection.""" name: Literal["IBEASelector"] = Field( default="IBEASelector", frozen=True, description="The name of the selection operator." ) """The name of the selection operator.""" population_size: int = Field(gt=0, description="The population size.") """The population size.""" kappa: float = Field(default=0.05, description="The kappa parameter for IBEA.") """The kappa parameter for IBEA.""" binary_indicator: Literal["eps", "hv"] = Field(default="eps", description="The binary indicator for IBEA.") """The binary indicator for IBEA.""" ``` #### binary_indicator ``` binary_indicator: Literal["eps", "hv"] = Field( default="eps", description="The binary indicator for IBEA.", ) ``` The binary indicator for IBEA. #### kappa ``` kappa: float = Field( default=0.05, description="The kappa parameter for IBEA.", ) ``` The kappa parameter for IBEA. #### name ``` name: Literal["IBEASelector"] = Field( default="IBEASelector", frozen=True, description="The name of the selection operator.", ) ``` The name of the selection operator. #### population_size ``` population_size: int = Field( gt=0, description="The population size." ) ``` The population size. ### MOEADSelectorOptions Bases: `BaseModel` Options for the MOEA/D selector. Only `TemplateMOEADOptions` takes this selector, since its replacement works one offspring at a time inside the MOEA/D loop. It is therefore not a member of `SelectorOptions`. Source code in `desdeo/emo/options/selection.py` ``` class MOEADSelectorOptions(BaseModel): """Options for the MOEA/D selector. Only `TemplateMOEADOptions` takes this selector, since its replacement works one offspring at a time inside the MOEA/D loop. It is therefore not a member of `SelectorOptions`. """ model_config = ConfigDict(use_attribute_docstrings=True) name: Literal["MOEADSelector"] = Field( default="MOEADSelector", frozen=True, description="The name of the selection operator." ) """The name of the selection operator.""" reference_vector_options: ReferenceVectorOptions = Field( default=ReferenceVectorOptions(vector_type="planar"), description="Options for the weight vectors." ) """Options for the weight vectors. Their number is the population size. The vectors are always normalized to sum to one, whatever `vector_type` says.""" neighbourhood_size: int = Field(default=20, ge=2, description="The neighbourhood size T.") """The neighbourhood size `T`: how many of the closest weight vectors, the subproblem's own included, form a subproblem's neighbourhood.""" neighbourhood_probability: float = Field( default=1.0, ge=0.0, le=1.0, description="The probability delta of mating within the neighbourhood." ) """The probability `delta` that the mating pool and the replacement range are the neighbourhood rather than the whole population. 1.0 in the original MOEA/D, 0.9 in MOEA/D-DE.""" max_replacements: int | None = Field( default=None, ge=1, description="The maximum number n_r of solutions one offspring may replace." ) """The maximum number `n_r` of solutions one offspring may replace. None places no cap, as in the original MOEA/D; MOEA/D-DE uses 2.""" aggregation: Literal["tchebycheff", "pbi", "weighted_sum"] = Field( default="tchebycheff", description="The aggregation function of the subproblems." ) """The aggregation function of the subproblems.""" pbi_penalty: float = Field(default=5.0, gt=0.0, description="The penalty theta of the PBI function.") """The penalty `theta` of the PBI aggregation function. Only used with `aggregation="pbi"`.""" ``` #### aggregation ``` aggregation: Literal[ "tchebycheff", "pbi", "weighted_sum" ] = Field( default="tchebycheff", description="The aggregation function of the subproblems.", ) ``` The aggregation function of the subproblems. #### max_replacements ``` max_replacements: int | None = Field( default=None, ge=1, description="The maximum number n_r of solutions one offspring may replace.", ) ``` The maximum number `n_r` of solutions one offspring may replace. None places no cap, as in the original MOEA/D; MOEA/D-DE uses 2. #### name ``` name: Literal["MOEADSelector"] = Field( default="MOEADSelector", frozen=True, description="The name of the selection operator.", ) ``` The name of the selection operator. #### neighbourhood_probability ``` neighbourhood_probability: float = Field( default=1.0, ge=0.0, le=1.0, description="The probability delta of mating within the neighbourhood.", ) ``` The probability `delta` that the mating pool and the replacement range are the neighbourhood rather than the whole population. 1.0 in the original MOEA/D, 0.9 in MOEA/D-DE. #### neighbourhood_size ``` neighbourhood_size: int = Field( default=20, ge=2, description="The neighbourhood size T.", ) ``` The neighbourhood size `T`: how many of the closest weight vectors, the subproblem's own included, form a subproblem's neighbourhood. #### pbi_penalty ``` pbi_penalty: float = Field( default=5.0, gt=0.0, description="The penalty theta of the PBI function.", ) ``` The penalty `theta` of the PBI aggregation function. Only used with `aggregation="pbi"`. #### reference_vector_options ``` reference_vector_options: ReferenceVectorOptions = Field( default=ReferenceVectorOptions(vector_type="planar"), description="Options for the weight vectors.", ) ``` Options for the weight vectors. Their number is the population size. The vectors are always normalized to sum to one, whatever `vector_type` says. ### ModifiedWASFGASelectorOptions Bases: `BaseModel` Options for the environmental selection of Modified WASF-GA (IRA-EMO). Source code in `desdeo/emo/options/selection.py` ``` class ModifiedWASFGASelectorOptions(BaseModel): """Options for the environmental selection of Modified WASF-GA (IRA-EMO).""" model_config = ConfigDict(use_attribute_docstrings=True) name: Literal["ModifiedWASFGASelector"] = Field( default="ModifiedWASFGASelector", frozen=True, description="The name of the selection operator." ) """The name of the selection operator.""" population_size: int = Field(gt=0, description="The number of solutions selected each generation.") """The number of solutions selected each generation.""" number_of_weights: int | None = Field( default=None, gt=1, description="The number of weight vectors, split evenly between the two reference points. None uses the " "population size.", ) """The number of weight vectors, split evenly between the two reference points. None uses the population size, which is the reference code's default.""" aspiration_levels: dict[str, float] | None = Field( default=None, description="The aspiration level of every objective, keyed by symbol. None uses the estimated ideal point.", ) """The aspiration level of every objective, keyed by symbol and in the objective's own sense. None uses the ideal point estimated from the run.""" reservation_levels: dict[str, float] | None = Field( default=None, description="The reservation level of every objective, keyed by symbol. None uses the estimated nadir point.", ) """The reservation level of every objective, keyed by symbol and in the objective's own sense. None uses the nadir point estimated from the run.""" rho: float = Field(default=0.001, gt=0.0, description="The augmentation coefficient of the ASF.") """The augmentation coefficient of the achievement scalarizing function. 0.001 is the reference code's value.""" epsilon: float | None = Field( default=None, gt=0.0, description="The smallest component of the vectors whose inverses are the weights. None uses 0.01 for two " "objectives and 0.005 for more.", ) """The smallest component of the vectors whose inverses are the weights. None uses the reference code's values, 0.01 for two objectives and 0.005 for more.""" ``` #### aspiration_levels ``` aspiration_levels: dict[str, float] | None = Field( default=None, description="The aspiration level of every objective, keyed by symbol. None uses the estimated ideal point.", ) ``` The aspiration level of every objective, keyed by symbol and in the objective's own sense. None uses the ideal point estimated from the run. #### epsilon ``` epsilon: float | None = Field( default=None, gt=0.0, description="The smallest component of the vectors whose inverses are the weights. None uses 0.01 for two objectives and 0.005 for more.", ) ``` The smallest component of the vectors whose inverses are the weights. None uses the reference code's values, 0.01 for two objectives and 0.005 for more. #### name ``` name: Literal["ModifiedWASFGASelector"] = Field( default="ModifiedWASFGASelector", frozen=True, description="The name of the selection operator.", ) ``` The name of the selection operator. #### number_of_weights ``` number_of_weights: int | None = Field( default=None, gt=1, description="The number of weight vectors, split evenly between the two reference points. None uses the population size.", ) ``` The number of weight vectors, split evenly between the two reference points. None uses the population size, which is the reference code's default. #### population_size ``` population_size: int = Field( gt=0, description="The number of solutions selected each generation.", ) ``` The number of solutions selected each generation. #### reservation_levels ``` reservation_levels: dict[str, float] | None = Field( default=None, description="The reservation level of every objective, keyed by symbol. None uses the estimated nadir point.", ) ``` The reservation level of every objective, keyed by symbol and in the objective's own sense. None uses the nadir point estimated from the run. #### rho ``` rho: float = Field( default=0.001, gt=0.0, description="The augmentation coefficient of the ASF.", ) ``` The augmentation coefficient of the achievement scalarizing function. 0.001 is the reference code's value. ### NSGA2SelectorOptions Bases: `BaseModel` Options for NSGA-II Selection. Source code in `desdeo/emo/options/selection.py` ``` class NSGA2SelectorOptions(BaseModel): """Options for NSGA-II Selection.""" name: Literal["NSGA2Selector"] = Field( default="NSGA2Selector", frozen=True, description="The name of the selection operator." ) """The name of the selection operator.""" population_size: int = Field(gt=0, description="The population size.") """The population size.""" ``` #### name ``` name: Literal["NSGA2Selector"] = Field( default="NSGA2Selector", frozen=True, description="The name of the selection operator.", ) ``` The name of the selection operator. #### population_size ``` population_size: int = Field( gt=0, description="The population size." ) ``` The population size. ### NSGA3SelectorOptions Bases: `BaseModel` Options for NSGA-III Selection. Source code in `desdeo/emo/options/selection.py` ``` class NSGA3SelectorOptions(BaseModel): """Options for NSGA-III Selection.""" name: Literal["NSGA3Selector"] = Field( default="NSGA3Selector", frozen=True, description="The name of the selection operator." ) """The name of the selection operator.""" reference_vector_options: ReferenceVectorOptions = Field( default=ReferenceVectorOptions(), description="Options for the reference vectors." ) """Options for the reference vectors.""" invert_reference_vectors: bool = Field( default=False, description="Whether to invert the reference vectors (inverted triangle)." ) """Whether to invert the reference vectors (inverted triangle).""" ``` #### invert_reference_vectors ``` invert_reference_vectors: bool = Field( default=False, description="Whether to invert the reference vectors (inverted triangle).", ) ``` Whether to invert the reference vectors (inverted triangle). #### name ``` name: Literal["NSGA3Selector"] = Field( default="NSGA3Selector", frozen=True, description="The name of the selection operator.", ) ``` The name of the selection operator. #### reference_vector_options ``` reference_vector_options: ReferenceVectorOptions = Field( default=ReferenceVectorOptions(), description="Options for the reference vectors.", ) ``` Options for the reference vectors. ### RVEASelectorOptions Bases: `BaseModel` Options for RVEA Selection. Source code in `desdeo/emo/options/selection.py` ``` class RVEASelectorOptions(BaseModel): """Options for RVEA Selection.""" model_config = ConfigDict(use_enum_values=True) name: Literal["RVEASelector"] = Field( default="RVEASelector", frozen=True, description="The name of the selection operator." ) """The name of the selection operator.""" reference_vector_options: ReferenceVectorOptions = Field( default=ReferenceVectorOptions(), description="Options for the reference vectors." ) """Options for the reference vectors.""" parameter_adaptation_strategy: ParameterAdaptationStrategy = Field( default=ParameterAdaptationStrategy.GENERATION_BASED, description="The parameter adaptation strategy to use." ) """Whether the angle penalized distance is adapted per generation or per function evaluation.""" alpha: float = Field(default=2.0, gt=0.0, description="The alpha parameter in the angle penalized distance.") """The alpha parameter in the angle penalized distance.""" ``` #### alpha ``` alpha: float = Field( default=2.0, gt=0.0, description="The alpha parameter in the angle penalized distance.", ) ``` The alpha parameter in the angle penalized distance. #### name ``` name: Literal["RVEASelector"] = Field( default="RVEASelector", frozen=True, description="The name of the selection operator.", ) ``` The name of the selection operator. #### parameter_adaptation_strategy ``` parameter_adaptation_strategy: ParameterAdaptationStrategy = Field( default=ParameterAdaptationStrategy.GENERATION_BASED, description="The parameter adaptation strategy to use.", ) ``` Whether the angle penalized distance is adapted per generation or per function evaluation. #### reference_vector_options ``` reference_vector_options: ReferenceVectorOptions = Field( default=ReferenceVectorOptions(), description="Options for the reference vectors.", ) ``` Options for the reference vectors. ### SMSEMOASelectorOptions Bases: `BaseModel` Options for SMS-EMOA Selection. Source code in `desdeo/emo/options/selection.py` ``` class SMSEMOASelectorOptions(BaseModel): """Options for SMS-EMOA Selection.""" model_config = {"use_attribute_docstrings": True} name: Literal["SMSEMOASelector"] = Field(default="SMSEMOASelector", frozen=True) """The name of the selection operator.""" normalised_reference_point_component: float = Field(default=2, gt=1.0) """The reference point component used for hypervolume calculation. The solutions are normalized to the range [0, 1] and the reference point is set to a vector of ones multiplied by this component.""" ``` #### name ``` name: Literal["SMSEMOASelector"] = Field( default="SMSEMOASelector", frozen=True ) ``` The name of the selection operator. #### normalised_reference_point_component ``` normalised_reference_point_component: float = Field( default=2, gt=1.0 ) ``` The reference point component used for hypervolume calculation. The solutions are normalized to the range [0, 1] and the reference point is set to a vector of ones multiplied by this component. ### SPEA2SelectorOptions Bases: `BaseModel` Options for SPEA2 environmental selection. Source code in `desdeo/emo/options/selection.py` ``` class SPEA2SelectorOptions(BaseModel): """Options for SPEA2 environmental selection.""" model_config = ConfigDict(use_attribute_docstrings=True) name: Literal["SPEA2Selector"] = Field( default="SPEA2Selector", frozen=True, description="The name of the selection operator." ) """The name of the selection operator.""" population_size: int = Field(gt=0, description="The archive size.") """The archive size, N-bar in the paper. The population size N is the mating selection's `winner_size`.""" ``` #### name ``` name: Literal["SPEA2Selector"] = Field( default="SPEA2Selector", frozen=True, description="The name of the selection operator.", ) ``` The name of the selection operator. #### population_size ``` population_size: int = Field( gt=0, description="The archive size." ) ``` The archive size, N-bar in the paper. The population size N is the mating selection's `winner_size`. ### selection_constructor ``` selection_constructor( problem: Problem, options: SelectorOptions | MOEADSelectorOptions, publisher: Publisher, verbosity: int, seed: int, ) -> BaseSelector ``` Construct a selection operator from given options. Parameters: | Name | Type | Description | Default | | ----------- | ----------------- | --------------------------------------- | ---------- | | `problem` | `Problem` | The optimization problem. | *required* | | `options` | `SelectorOptions` | The options for the selection operator. | *required* | | `publisher` | `Publisher` | The publisher to use for the operator. | *required* | | `verbosity` | `int` | The verbosity level. | *required* | | `seed` | `int` | The random seed. | *required* | Returns: | Name | Type | Description | | -------------- | -------------- | ----------------------------------- | | `BaseSelector` | `BaseSelector` | The constructed selection operator. | Raises: | Type | Description | | ------------ | -------------------------------------------------- | | `ValueError` | If an unknown selection operator name is provided. | Source code in `desdeo/emo/options/selection.py` ``` def selection_constructor( problem: Problem, options: SelectorOptions | MOEADSelectorOptions, publisher: Publisher, verbosity: int, seed: int ) -> BaseSelector: """Construct a selection operator from given options. Args: problem (Problem): The optimization problem. options (SelectorOptions): The options for the selection operator. publisher (Publisher): The publisher to use for the operator. verbosity (int): The verbosity level. seed (int): The random seed. Returns: BaseSelector: The constructed selection operator. Raises: ValueError: If an unknown selection operator name is provided. """ selection_types = { "RVEASelector": RVEASelector, "NSGA2Selector": NSGA2Selector, "NSGA3Selector": NSGA3Selector, "IBEASelector": IBEASelector, "SMSEMOASelector": SMSEMOASelector, "MOEADSelector": MOEADSelector, "SPEA2Selector": SPEA2Selector, "AGEMOEA2Selector": AGEMOEA2Selector, "HypESelector": HypESelector, "ModifiedWASFGASelector": ModifiedWASFGASelector, } options: dict = options.model_dump() name = options.pop("name") if name == "IBEASelector": indi = options.pop("binary_indicator") match indi: case "eps": options["binary_indicator"] = self_epsilon case "hv": options["binary_indicator"] = self_hv case _: raise ValueError(f"Unknown binary indicator: {indi}") return selection_types[name](problem=problem, publisher=publisher, seed=seed, verbosity=verbosity, **options) ``` ## Termination Criteria JSON Schema for termination operator options. ### CompositeTerminatorOptions Bases: `BaseModel` Options for composite terminator operator. Source code in `desdeo/emo/options/termination.py` ``` class CompositeTerminatorOptions(BaseModel): """Options for composite terminator operator.""" name: Literal["CompositeTerminator"] = Field( default="CompositeTerminator", frozen=True, description="The name of the termination operator." ) """The name of the termination operator.""" terminators: list[ MaxEvaluationsTerminatorOptions | MaxGenerationsTerminatorOptions | MaxTimeTerminatorOptions | ExternalCheckTerminatorOptions ] = Field(default_factory=lambda: [MaxGenerationsTerminatorOptions()], description="List of terminators.") """List of terminators.""" mode: Literal["all", "any"] = Field(default="any", description="Whether to use logical AND or OR.") """Whether to use logical AND or OR.""" @model_validator(mode="after") def check_unique_terminator_types(self): """Ensure that all terminator types in the composite are unique.""" types_seen = set() for term in self.terminators: t = type(term) if t in types_seen: raise ValueError(f"Duplicate terminator type: {t.__name__}") types_seen.add(t) return self ``` #### mode ``` mode: Literal["all", "any"] = Field( default="any", description="Whether to use logical AND or OR.", ) ``` Whether to use logical AND or OR. #### name ``` name: Literal["CompositeTerminator"] = Field( default="CompositeTerminator", frozen=True, description="The name of the termination operator.", ) ``` The name of the termination operator. #### terminators ``` terminators: list[ MaxEvaluationsTerminatorOptions | MaxGenerationsTerminatorOptions | MaxTimeTerminatorOptions | ExternalCheckTerminatorOptions ] = Field( default_factory=lambda: [ MaxGenerationsTerminatorOptions() ], description="List of terminators.", ) ``` List of terminators. #### check_unique_terminator_types ``` check_unique_terminator_types() ``` Ensure that all terminator types in the composite are unique. Source code in `desdeo/emo/options/termination.py` ``` @model_validator(mode="after") def check_unique_terminator_types(self): """Ensure that all terminator types in the composite are unique.""" types_seen = set() for term in self.terminators: t = type(term) if t in types_seen: raise ValueError(f"Duplicate terminator type: {t.__name__}") types_seen.add(t) return self ``` ### ExternalCheckTerminatorOptions Bases: `BaseModel` Options for external check terminator operator. Note that the check function must be provided separately. Source code in `desdeo/emo/options/termination.py` ``` class ExternalCheckTerminatorOptions(BaseModel): """Options for external check terminator operator. Note that the check function must be provided separately.""" name: Literal["ExternalCheckTerminator"] = Field( default="ExternalCheckTerminator", frozen=True, description="The name of the termination operator." ) """The name of the termination operator.""" ``` #### name ``` name: Literal["ExternalCheckTerminator"] = Field( default="ExternalCheckTerminator", frozen=True, description="The name of the termination operator.", ) ``` The name of the termination operator. ### MaxEvaluationsTerminatorOptions Bases: `BaseModel` Options for max evaluations terminator operator. Source code in `desdeo/emo/options/termination.py` ``` class MaxEvaluationsTerminatorOptions(BaseModel): """Options for max evaluations terminator operator.""" name: Literal["MaxEvaluationsTerminator"] = Field( default="MaxEvaluationsTerminator", frozen=True, description="The name of the termination operator." ) """The name of the termination operator.""" max_evaluations: int = Field(default=10000, gt=0, description="The maximum number of evaluations allowed.") """The maximum number of evaluations allowed.""" ``` #### max_evaluations ``` max_evaluations: int = Field( default=10000, gt=0, description="The maximum number of evaluations allowed.", ) ``` The maximum number of evaluations allowed. #### name ``` name: Literal["MaxEvaluationsTerminator"] = Field( default="MaxEvaluationsTerminator", frozen=True, description="The name of the termination operator.", ) ``` The name of the termination operator. ### MaxGenerationsTerminatorOptions Bases: `BaseModel` Options for max generations terminator operator. Source code in `desdeo/emo/options/termination.py` ``` class MaxGenerationsTerminatorOptions(BaseModel): """Options for max generations terminator operator.""" name: Literal["MaxGenerationsTerminator"] = Field( default="MaxGenerationsTerminator", frozen=True, description="The name of the termination operator." ) """The name of the termination operator.""" max_generations: int = Field(default=100, gt=0, description="The maximum number of generations allowed.") """The maximum number of generations allowed.""" ``` #### max_generations ``` max_generations: int = Field( default=100, gt=0, description="The maximum number of generations allowed.", ) ``` The maximum number of generations allowed. #### name ``` name: Literal["MaxGenerationsTerminator"] = Field( default="MaxGenerationsTerminator", frozen=True, description="The name of the termination operator.", ) ``` The name of the termination operator. ### MaxTimeTerminatorOptions Bases: `BaseModel` Options for max time terminator operator. Source code in `desdeo/emo/options/termination.py` ``` class MaxTimeTerminatorOptions(BaseModel): """Options for max time terminator operator.""" name: Literal["MaxTimeTerminator"] = Field( default="MaxTimeTerminator", frozen=True, description="The name of the termination operator." ) """The name of the termination operator.""" max_time_in_seconds: float = Field(default=30.0, gt=0, description="The maximum time allowed (in seconds).") """The maximum time allowed (in seconds). Named to match `MaxTimeTerminator.__init__`, because `terminator_constructor` splats `model_dump()` as keyword arguments. It was `max_time` until that mismatch was found, which made every construction through this options model raise `TypeError`.""" ``` #### max_time_in_seconds ``` max_time_in_seconds: float = Field( default=30.0, gt=0, description="The maximum time allowed (in seconds).", ) ``` The maximum time allowed (in seconds). Named to match `MaxTimeTerminator.__init__`, because `terminator_constructor` splats `model_dump()` as keyword arguments. It was `max_time` until that mismatch was found, which made every construction through this options model raise `TypeError`. #### name ``` name: Literal["MaxTimeTerminator"] = Field( default="MaxTimeTerminator", frozen=True, description="The name of the termination operator.", ) ``` The name of the termination operator. ### terminator_constructor ``` terminator_constructor( options: TerminatorOptions, publisher: Publisher, external_check: Callable | None = None, ) -> BaseTerminator ``` Construct a termination operator. Parameters: | Name | Type | Description | Default | | ---------------- | ------------------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | | `options` | `TerminatorOptions` | Options for the termination operator. | *required* | | `publisher` | `Publisher` | Publisher instance for the termination operator. | *required* | | `external_check` | \`Callable | None\` | External check function for the termination operator. Defaults to None. Only required if using ExternalCheckTerminator. | Raises: | Type | Description | | ------------ | ------------------------------------------------------------ | | `ValueError` | If the options are invalid. | | `ValueError` | If the external check function is required but not provided. | Returns: | Name | Type | Description | | ---------------- | ---------------- | ------------------------------------- | | `BaseTerminator` | `BaseTerminator` | Instance of the termination operator. | Source code in `desdeo/emo/options/termination.py` ``` def terminator_constructor( options: TerminatorOptions, publisher: Publisher, external_check: Callable | None = None ) -> BaseTerminator: """Construct a termination operator. Args: options (TerminatorOptions): Options for the termination operator. publisher (Publisher): Publisher instance for the termination operator. external_check (Callable | None, optional): External check function for the termination operator. Defaults to None. Only required if using ExternalCheckTerminator. Raises: ValueError: If the options are invalid. ValueError: If the external check function is required but not provided. Returns: BaseTerminator: Instance of the termination operator. """ terminators = { "MaxGenerationsTerminator": MaxGenerationsTerminator, "MaxEvaluationsTerminator": MaxEvaluationsTerminator, "MaxTimeTerminator": MaxTimeTerminator, "ExternalCheckTerminator": ExternalCheckTerminator, "CompositeTerminator": CompositeTerminator, } # The composite recurses on its children, so it has to branch *before* `model_dump()`: dumping is # recursive, and a child turned into a plain dict has no `.model_dump()` for the recursive call # to reach. if options.name == "CompositeTerminator": sub_terminators = [terminator_constructor(child, publisher, external_check) for child in options.terminators] return CompositeTerminator(terminators=sub_terminators, publisher=publisher, mode=options.mode) fields: dict = options.model_dump() name = fields.pop("name") if name == "ExternalCheckTerminator": if external_check is None: raise ValueError("External check function must be provided for ExternalCheckTerminator.") return ExternalCheckTerminator(check_function=external_check, publisher=publisher, **fields) if name not in terminators: raise ValueError(f"Unknown terminator name: {name}") return terminators[name](publisher=publisher, **fields) ``` ### desdeo.adm.base_adm Base class for Artificial Decision Makers (ADMs). This module provides the abstract base class that defines the structure and required methods for implementing an artificial decision maker, which generates preference information for interactive multiobjective optimization methods. #### BaseADM Bases: `ABC` Abstract base class for Artificial Decision Makers (ADMs). This class provides the basic structure and required methods for implementing an ADM. Subclasses must implement the abstract methods to define specific ADM behavior. Attributes: | Name | Type | Description | | ------------------- | ----------- | -------------------------------------------- | | `problem` | `Problem` | The optimization problem to solve. | | `it_learning_phase` | `int` | Number of iterations for the learning phase. | | `it_decision_phase` | `int` | Number of iterations for the decision phase. | | `iteration_counter` | `int` | Counter for the current iteration. | | `rng` | `Generator` | Random number generator used by subclasses. | Properties max_iterations (int): Total number of iterations (learning + decision). Source code in `desdeo/adm/base_adm.py` ``` class BaseADM(ABC): """Abstract base class for Artificial Decision Makers (ADMs). This class provides the basic structure and required methods for implementing an ADM. Subclasses must implement the abstract methods to define specific ADM behavior. Attributes: problem (Problem): The optimization problem to solve. it_learning_phase (int): Number of iterations for the learning phase. it_decision_phase (int): Number of iterations for the decision phase. iteration_counter (int): Counter for the current iteration. rng (np.random.Generator): Random number generator used by subclasses. Properties: max_iterations (int): Total number of iterations (learning + decision). """ def __init__( self, problem: Problem, it_learning_phase: int, it_decision_phase: int, seed: int | None = None, ): """Initialize the ADM with the given problem and phase lengths. Args: problem (Problem): The optimization problem to solve. it_learning_phase (int): Number of iterations for the learning phase. it_decision_phase (int): Number of iterations for the decision phase. seed (int | None): Optional seed for the random number generator used by subclasses. Defaults to None. """ self.problem = problem self.it_learning_phase = it_learning_phase self.it_decision_phase = it_decision_phase self.iteration_counter = 0 self.rng = np.random.default_rng(seed) @property def max_iterations(self): """int: Total number of iterations (learning + decision).""" return self.it_learning_phase + self.it_decision_phase def has_next(self) -> bool: """Check if there are more iterations left to run. Returns: bool: True if more iterations remain, False otherwise. """ return self.iteration_counter < self.max_iterations @abstractmethod def generate_initial_preference(self): """Generate the initial preference information for the ADM. This method must be implemented by subclasses. """ @abstractmethod def get_next_preference(self): """Get the next preference value according to the current phase. This method must be implemented by subclasses. """ @abstractmethod def generate_preference_learning(self): """Generate preference information during the learning phase. This method must be implemented by subclasses. """ @abstractmethod def generate_preference_decision(self): """Generate preference information during the decision phase. This method must be implemented by subclasses. """ ``` ##### max_iterations ``` max_iterations ``` int: Total number of iterations (learning + decision). ##### __init__ ``` __init__( problem: Problem, it_learning_phase: int, it_decision_phase: int, seed: int | None = None, ) ``` Initialize the ADM with the given problem and phase lengths. Parameters: | Name | Type | Description | Default | | ------------------- | --------- | -------------------------------------------- | ----------------------------------------------------------------------------------- | | `problem` | `Problem` | The optimization problem to solve. | *required* | | `it_learning_phase` | `int` | Number of iterations for the learning phase. | *required* | | `it_decision_phase` | `int` | Number of iterations for the decision phase. | *required* | | `seed` | \`int | None\` | Optional seed for the random number generator used by subclasses. Defaults to None. | Source code in `desdeo/adm/base_adm.py` ``` def __init__( self, problem: Problem, it_learning_phase: int, it_decision_phase: int, seed: int | None = None, ): """Initialize the ADM with the given problem and phase lengths. Args: problem (Problem): The optimization problem to solve. it_learning_phase (int): Number of iterations for the learning phase. it_decision_phase (int): Number of iterations for the decision phase. seed (int | None): Optional seed for the random number generator used by subclasses. Defaults to None. """ self.problem = problem self.it_learning_phase = it_learning_phase self.it_decision_phase = it_decision_phase self.iteration_counter = 0 self.rng = np.random.default_rng(seed) ``` ##### generate_initial_preference ``` generate_initial_preference() ``` Generate the initial preference information for the ADM. This method must be implemented by subclasses. Source code in `desdeo/adm/base_adm.py` ``` @abstractmethod def generate_initial_preference(self): """Generate the initial preference information for the ADM. This method must be implemented by subclasses. """ ``` ##### generate_preference_decision ``` generate_preference_decision() ``` Generate preference information during the decision phase. This method must be implemented by subclasses. Source code in `desdeo/adm/base_adm.py` ``` @abstractmethod def generate_preference_decision(self): """Generate preference information during the decision phase. This method must be implemented by subclasses. """ ``` ##### generate_preference_learning ``` generate_preference_learning() ``` Generate preference information during the learning phase. This method must be implemented by subclasses. Source code in `desdeo/adm/base_adm.py` ``` @abstractmethod def generate_preference_learning(self): """Generate preference information during the learning phase. This method must be implemented by subclasses. """ ``` ##### get_next_preference ``` get_next_preference() ``` Get the next preference value according to the current phase. This method must be implemented by subclasses. Source code in `desdeo/adm/base_adm.py` ``` @abstractmethod def get_next_preference(self): """Get the next preference value according to the current phase. This method must be implemented by subclasses. """ ``` ##### has_next ``` has_next() -> bool ``` Check if there are more iterations left to run. Returns: | Name | Type | Description | | ------ | ------ | ------------------------------------------------ | | `bool` | `bool` | True if more iterations remain, False otherwise. | Source code in `desdeo/adm/base_adm.py` ``` def has_next(self) -> bool: """Check if there are more iterations left to run. Returns: bool: True if more iterations remain, False otherwise. """ return self.iteration_counter < self.max_iterations ``` ### desdeo.adm.adm_chen Artificial decision maker (ADM) based on the approach by Chen et al. This module implements the artificial decision maker proposed by Chen et al. References Chen, L., Miettinen, K., Xin, B., & Ojalehto, V. (2023). Comparing reference point based interactive multiobjective optimization methods without a human decision maker. European Journal of Operational Research, 307(1), 327-345. IMPORTANT: This module is a work in progress. There are multiple things not clear in the article that need further clarification. #### ADMChen Bases: `BaseADM` Artificial Decision Maker implementation based on Chen et al. (2023). This ADM simulates human decision-making behavior in interactive multiobjective optimization by operating in two phases: learning and decision-making. During the learning phase, it explores the Pareto front by identifying neighboring solutions with maximum normalized Euclidean distance. In the decision phase, it selects solutions based on a utility function that minimizes disutility. Attributes: | Name | Type | Description | | ------------------- | --------- | ------------------------------------------------------------- | | `true_ideal` | `ndarray` | True ideal point computed from the problem. | | `true_nadir` | `ndarray` | True nadir point computed from the problem. | | `num_objectives` | `int` | Number of objectives in the problem. | | `num_variables` | `int` | Number of variables in the problem. | | `preference` | `ndarray` | Current reference point preference. | | `weights` | `ndarray` | Objective weights (equal weights by default). | | `UF_max` | `float` | Maximum utility function value on the Pareto front. | | `UF_opt` | `float` | Optimal (minimum) utility function value on the Pareto front. | | `extreme_solutions` | `ndarray` | Extreme solutions from the Pareto front. | Parameters: | Name | Type | Description | Default | | ------------------------- | ------------------- | -------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The multiobjective optimization problem. | *required* | | `it_learning_phase` | `int` | Number of iterations for the learning phase. | *required* | | `it_decision_phase` | `int` | Number of iterations for the decision phase. | *required* | | `pareto_front` | `ndarray` | Known Pareto front solutions for initialization. | *required* | | `initial_reference_point` | `Optional[ndarray]` | Initial reference point. If None, a random point between ideal and nadir is generated. | `None` | Raises: | Type | Description | | ------------ | --------------------------------------------------------------------- | | `ValueError` | If the initial reference point is not between ideal and nadir points. | Example > > > problem = Problem(...) # Define your problem pareto_front = np.array(\[[1, 2], [2, 1], [1.5, 1.5]\]) adm = ADMChen(problem, it_learning_phase=5, it_decision_phase=3, ... pareto_front=pareto_front) preference = adm.get_next_preference(current_front) Source code in `desdeo/adm/adm_chen.py` ``` class ADMChen(BaseADM): """Artificial Decision Maker implementation based on Chen et al. (2023). This ADM simulates human decision-making behavior in interactive multiobjective optimization by operating in two phases: learning and decision-making. During the learning phase, it explores the Pareto front by identifying neighboring solutions with maximum normalized Euclidean distance. In the decision phase, it selects solutions based on a utility function that minimizes disutility. Attributes: true_ideal (np.ndarray): True ideal point computed from the problem. true_nadir (np.ndarray): True nadir point computed from the problem. num_objectives (int): Number of objectives in the problem. num_variables (int): Number of variables in the problem. preference (np.ndarray): Current reference point preference. weights (np.ndarray): Objective weights (equal weights by default). UF_max (float): Maximum utility function value on the Pareto front. UF_opt (float): Optimal (minimum) utility function value on the Pareto front. extreme_solutions (np.ndarray): Extreme solutions from the Pareto front. Args: problem (Problem): The multiobjective optimization problem. it_learning_phase (int): Number of iterations for the learning phase. it_decision_phase (int): Number of iterations for the decision phase. pareto_front (np.ndarray): Known Pareto front solutions for initialization. initial_reference_point (Optional[np.ndarray]): Initial reference point. If None, a random point between ideal and nadir is generated. Raises: ValueError: If the initial reference point is not between ideal and nadir points. Example: >>> problem = Problem(...) # Define your problem >>> pareto_front = np.array([[1, 2], [2, 1], [1.5, 1.5]]) >>> adm = ADMChen(problem, it_learning_phase=5, it_decision_phase=3, ... pareto_front=pareto_front) >>> preference = adm.get_next_preference(current_front) """ def __init__( self, problem: Problem, it_learning_phase: int, it_decision_phase: int, pareto_front: np.ndarray, initial_reference_point: np.ndarray | None = None, seed: int | None = None, ): """Initialize the artificial decision maker proposed by Chen et al. Args: problem (Problem): The multiobjective optimization problem. it_learning_phase (int): Number of iterations for the learning phase. it_decision_phase (int): Number of iterations for the decision phase. pareto_front (np.ndarray): Known Pareto front solutions for initialization. initial_reference_point (np.ndarray | None): Initial reference point. If None, a random point between the ideal and nadir is generated. seed (int | None): Optional seed for the random number generator. Defaults to None. """ # Initialize problem with true ideal and nadir points self.true_ideal, self.true_nadir = payoff_table_method(problem) problem = problem.update_ideal_and_nadir(new_ideal=self.true_ideal, new_nadir=self.true_nadir) super().__init__(problem, it_learning_phase, it_decision_phase, seed=seed) # Store problem dimensions self.num_objectives = len(problem.objectives) self.num_variables = len(problem.variables) # Generate initial preference self.preference = self.generate_initial_preference(initial_reference_point) self.iteration_counter += 1 # Initialize equal weights for all objectives # NOTE: In the original article, weights were set manually self.weights = np.ones(self.num_objectives) / self.num_objectives # Compute utility function bounds on the Pareto front self.UF_max = np.max( [self.utility_function(sol, self.true_ideal, self.true_nadir, self.weights) for sol in pareto_front] ) self.UF_opt = np.min( [self.utility_function(sol, self.true_ideal, self.true_nadir, self.weights) for sol in pareto_front] ) # Store extreme solutions from the self.extreme_solutions = self.get_extreme_solutions(pareto_front) def generate_initial_preference(self, initial_reference_point: np.ndarray | None = None) -> np.ndarray: """Generate the initial reference point for the ADM. If an initial reference point is provided, it validates that the point lies between the ideal and nadir points. Otherwise, generates a random point within the feasible objective space. Args: initial_reference_point (Optional[np.ndarray]): User-specified initial reference point. Must be between ideal and nadir points. Returns: np.ndarray: Valid initial reference point. Raises: ValueError: If the provided reference point is outside the valid range. """ if initial_reference_point is not None: if not (self.true_ideal <= initial_reference_point <= self.true_nadir).all(): raise ValueError("Initial reference point must be between the ideal and nadir points.") return initial_reference_point # Generate random reference point between ideal and nadir return np.array( [ self.rng.uniform(min_val, max_val) for min_val, max_val in zip( self.problem.get_ideal_point().values(), self.problem.get_nadir_point().values(), strict=True, ) ] ) def get_next_preference(self, front: np.ndarray) -> np.ndarray: """Get the next preference (reference point) based on the current iteration phase. This method determines whether the ADM is in the learning or decision phase and calls the appropriate preference generation method. Args: front (np.ndarray): Current Pareto front approximation with shape (n_solutions, n_objectives). Returns: np.ndarray: Next reference point for the interactive method. """ if self.iteration_counter < self.it_learning_phase: self.preference = self.generate_preference_learning(front) else: self.preference = self.generate_preference_decision(front) self.iteration_counter += 1 return self.preference def get_extreme_solutions(self, front: np.ndarray) -> np.ndarray: """Extract extreme solutions from the Pareto front. An extreme solution is defined as the objective vector that minimizes one of the objective functions on the Pareto front. These solutions represent the boundaries of the achievable objective space. Args: front (np.ndarray): Pareto front with shape (n_solutions, n_objectives). Returns: np.ndarray: Array of extreme solutions with shape (n_objectives, n_objectives). Each row represents an extreme solution for one objective. Example: For a 2-objective problem with front = [[1, 3], [2, 2], [3, 1]]: - Extreme for obj 1: [1, 3] (min value 1 in first objective) - Extreme for obj 2: [3, 1] (min value 1 in second objective) """ extreme_solutions = [] for i in range(front.shape[1]): # For each objective idx_min_i = np.argmin(front[:, i]) # Find solution with minimum value extreme_solutions.append(front[idx_min_i]) return np.array(extreme_solutions) @staticmethod def normalized_euclidean_distance( za: np.ndarray, zb: np.ndarray, znad: np.ndarray, zstar: np.ndarray, eps: float | None = None ) -> float: """Compute normalized Euclidean distance between two solutions. The normalization is performed using the range between the utopian point (ideal - eps) and the nadir point. This ensures that the distance metric is scale-independent across different objectives. Args: za (np.ndarray): First solution vector of shape (n_objectives,). zb (np.ndarray): Second solution vector of shape (n_objectives,). znad (np.ndarray): Nadir point (worst values) of shape (n_objectives,). zstar (np.ndarray): Ideal point (best values) of shape (n_objectives,). eps (Optional[float]): Small positive value for utopian shift. Defaults to 1e-6 if None. Returns: float: Normalized Euclidean distance between za and zb. Note: The utopian point is computed as zstar - eps to ensure strict improvement over the ideal point. Division by zero is avoided by replacing zero denominators with 1e-12. """ za, zb, znad, zstar = map(np.asarray, (za, zb, znad, zstar)) if eps is None: eps = 1e-6 if np.isscalar(eps): eps = np.full_like(zstar, eps, dtype=float) # Compute utopian point (strictly better than ideal) z_utopian = zstar - eps # Compute normalization denominator denom = znad - z_utopian # Avoid division by zero when nadir ≈ utopian denom = np.where(denom <= 0, 1e-12, denom) # Compute normalized difference and Euclidean distance diff = (za - zb) / denom return np.sqrt(np.sum(diff**2)) @staticmethod def are_neighbors(za: np.ndarray, zb: np.ndarray, solutions: np.ndarray) -> bool: """Check if two solutions are neighbors in the context of a solution set. Two solutions za and zb are considered neighbors if their componentwise minimum is not dominated by any other solution in the set. Args: za (np.ndarray): First solution vector of shape (n_objectives,). zb (np.ndarray): Second solution vector of shape (n_objectives,). solutions (np.ndarray): Complete solution set with shape (n_solutions, n_objectives). Returns: bool: True if za and zb are neighbors, False otherwise. Note: The componentwise minimum z_ab = min(za, zb) represents a point that is at least as good as both za and zb in all objectives. If any other solution dominates z_ab, then za and zb are not considered neighbors. """ za = np.asarray(za) zb = np.asarray(zb) z_ab = np.minimum(za, zb) # Componentwise minimum for i in range(len(solutions)): zc = solutions[i] # Skip comparing to za and zb themselves if np.array_equal(zc, za) or np.array_equal(zc, zb): continue if nds.dominates(z_ab, zc): return False return True def generate_preference_learning(self, front: np.ndarray) -> np.ndarray: """Generate preference during the learning phase through systematic exploration. The learning phase explores the Pareto front by identifying neighboring solution pairs with the maximum normalized Euclidean distance. Args: front (np.ndarray): Current Pareto front with shape (n_solutions, n_objectives). Returns: np.ndarray: New reference point derived from the most distant neighbors. Note: The reference point is set as the componentwise minimum of the most distant neighboring pair, which represents an aspirational point that is better than both neighbors in all objectives. Todo: Validate that the same region has not been selected before to avoid redundant exploration. """ # Extend front with extreme solutions for comprehensive exploration extended_set = np.append(front, self.extreme_solutions, axis=0) neighbors_1 = [] neighbors_2 = [] euclidean_distances = [] # Find all neighboring pairs and compute their distances for i in range(extended_set.shape[0] - 1): z1 = extended_set[i, :] for j in range(i + 1, extended_set.shape[0]): z2 = extended_set[j, :] if self.are_neighbors(z1, z2, extended_set): neighbors_1.append(z1) neighbors_2.append(z2) euclidean_distances.append( self.normalized_euclidean_distance(z1, z2, self.true_nadir, self.true_ideal) ) # Select the pair with maximum distance for exploration max_distance_idx = np.argmax(euclidean_distances) # Generate reference point as componentwise minimum of the distant pair return np.minimum(neighbors_1[max_distance_idx], neighbors_2[max_distance_idx]) def utility_function( self, z: np.ndarray, zstar: np.ndarray, znad: np.ndarray, weight: np.ndarray, utility_type: str = "deterministic", eps: float | None = None, ) -> float: """Compute the utility function value for a given solution. The utility function measures the maximum weighted normalized distance from the utopian point. Lower values indicate better solutions. Args: z (np.ndarray): Solution vector of shape (n_objectives,). zstar (np.ndarray): Ideal point of shape (n_objectives,). znad (np.ndarray): Nadir point of shape (n_objectives,). weight (np.ndarray): Objective weights of shape (n_objectives,). utility_type (str): Type of utility function. Options: 'deterministic', 'random'. Defaults to 'deterministic'. eps (float | None): Small positive value for utopian shift. Defaults to 1e-6. Returns: float: Utility function value (lower is better). Note: When utility_type='random', Gaussian noise is added with standard deviation that decreases over iterations to simulate learning behavior. The noise magnitude is based on the utility function range. """ z, znad, zstar, weight = map(np.asarray, (z, znad, zstar, weight)) if eps is None: eps = 1e-6 if np.isscalar(eps): eps = np.full_like(zstar, eps, dtype=float) # Compute utopian point (strictly better than ideal) z_utopian = zstar - eps # Compute normalization denominator denom = znad - z_utopian # Avoid division by zero denom = np.where(denom <= 0, 1e-12, denom) # Compute weighted normalized distances diff = weight * ((z - z_utopian) / denom) u_minus = np.max(diff) # Chebyshev scalarization # Add random component if requested if utility_type == "random": # Noise decreases over iterations to simulate learning sigma = (self.UF_max - self.UF_opt) * 0.2 / (2 ** (self.it_decision_phase - 1)) noise = self.rng.uniform(low=0, high=sigma) u_minus = noise + u_minus return u_minus def generate_preference_decision(self, front: np.ndarray) -> np.ndarray: """Generate preference during the decision phase by selecting the best solution. In the decision phase, the ADM acts more decisively by evaluating all solutions in the current front using the utility function and selecting the one with minimum disutility (best utility value). This represents the final decision-making behavior after the learning phase. Args: front (np.ndarray): Current Pareto front with shape (n_solutions, n_objectives). Returns: np.ndarray: The solution with minimum disutility as the preferred reference point. Note: The returned solution represents the ADM's final preference and should be close to the decision maker's most preferred solution. """ min_disutility = np.inf preferred_solution = None # Evaluate all solutions and find the one with minimum disutility for solution in front: disutility = self.utility_function(solution, self.true_ideal, self.true_nadir, self.weights) if disutility < min_disutility: min_disutility = disutility preferred_solution = solution return preferred_solution ``` ##### __init__ ``` __init__( problem: Problem, it_learning_phase: int, it_decision_phase: int, pareto_front: ndarray, initial_reference_point: ndarray | None = None, seed: int | None = None, ) ``` Initialize the artificial decision maker proposed by Chen et al. Parameters: | Name | Type | Description | Default | | ------------------------- | --------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------ | | `problem` | `Problem` | The multiobjective optimization problem. | *required* | | `it_learning_phase` | `int` | Number of iterations for the learning phase. | *required* | | `it_decision_phase` | `int` | Number of iterations for the decision phase. | *required* | | `pareto_front` | `ndarray` | Known Pareto front solutions for initialization. | *required* | | `initial_reference_point` | \`ndarray | None\` | Initial reference point. If None, a random point between the ideal and nadir is generated. | | `seed` | \`int | None\` | Optional seed for the random number generator. Defaults to None. | Source code in `desdeo/adm/adm_chen.py` ``` def __init__( self, problem: Problem, it_learning_phase: int, it_decision_phase: int, pareto_front: np.ndarray, initial_reference_point: np.ndarray | None = None, seed: int | None = None, ): """Initialize the artificial decision maker proposed by Chen et al. Args: problem (Problem): The multiobjective optimization problem. it_learning_phase (int): Number of iterations for the learning phase. it_decision_phase (int): Number of iterations for the decision phase. pareto_front (np.ndarray): Known Pareto front solutions for initialization. initial_reference_point (np.ndarray | None): Initial reference point. If None, a random point between the ideal and nadir is generated. seed (int | None): Optional seed for the random number generator. Defaults to None. """ # Initialize problem with true ideal and nadir points self.true_ideal, self.true_nadir = payoff_table_method(problem) problem = problem.update_ideal_and_nadir(new_ideal=self.true_ideal, new_nadir=self.true_nadir) super().__init__(problem, it_learning_phase, it_decision_phase, seed=seed) # Store problem dimensions self.num_objectives = len(problem.objectives) self.num_variables = len(problem.variables) # Generate initial preference self.preference = self.generate_initial_preference(initial_reference_point) self.iteration_counter += 1 # Initialize equal weights for all objectives # NOTE: In the original article, weights were set manually self.weights = np.ones(self.num_objectives) / self.num_objectives # Compute utility function bounds on the Pareto front self.UF_max = np.max( [self.utility_function(sol, self.true_ideal, self.true_nadir, self.weights) for sol in pareto_front] ) self.UF_opt = np.min( [self.utility_function(sol, self.true_ideal, self.true_nadir, self.weights) for sol in pareto_front] ) # Store extreme solutions from the self.extreme_solutions = self.get_extreme_solutions(pareto_front) ``` ##### are_neighbors ``` are_neighbors( za: ndarray, zb: ndarray, solutions: ndarray ) -> bool ``` Check if two solutions are neighbors in the context of a solution set. Two solutions za and zb are considered neighbors if their componentwise minimum is not dominated by any other solution in the set. Parameters: | Name | Type | Description | Default | | ----------- | --------- | ------------------------------------------------------------- | ---------- | | `za` | `ndarray` | First solution vector of shape (n_objectives,). | *required* | | `zb` | `ndarray` | Second solution vector of shape (n_objectives,). | *required* | | `solutions` | `ndarray` | Complete solution set with shape (n_solutions, n_objectives). | *required* | Returns: | Name | Type | Description | | ------ | ------ | ------------------------------------------------- | | `bool` | `bool` | True if za and zb are neighbors, False otherwise. | Note The componentwise minimum z_ab = min(za, zb) represents a point that is at least as good as both za and zb in all objectives. If any other solution dominates z_ab, then za and zb are not considered neighbors. Source code in `desdeo/adm/adm_chen.py` ``` @staticmethod def are_neighbors(za: np.ndarray, zb: np.ndarray, solutions: np.ndarray) -> bool: """Check if two solutions are neighbors in the context of a solution set. Two solutions za and zb are considered neighbors if their componentwise minimum is not dominated by any other solution in the set. Args: za (np.ndarray): First solution vector of shape (n_objectives,). zb (np.ndarray): Second solution vector of shape (n_objectives,). solutions (np.ndarray): Complete solution set with shape (n_solutions, n_objectives). Returns: bool: True if za and zb are neighbors, False otherwise. Note: The componentwise minimum z_ab = min(za, zb) represents a point that is at least as good as both za and zb in all objectives. If any other solution dominates z_ab, then za and zb are not considered neighbors. """ za = np.asarray(za) zb = np.asarray(zb) z_ab = np.minimum(za, zb) # Componentwise minimum for i in range(len(solutions)): zc = solutions[i] # Skip comparing to za and zb themselves if np.array_equal(zc, za) or np.array_equal(zc, zb): continue if nds.dominates(z_ab, zc): return False return True ``` ##### generate_initial_preference ``` generate_initial_preference( initial_reference_point: ndarray | None = None, ) -> np.ndarray ``` Generate the initial reference point for the ADM. If an initial reference point is provided, it validates that the point lies between the ideal and nadir points. Otherwise, generates a random point within the feasible objective space. Parameters: | Name | Type | Description | Default | | ------------------------- | ------------------- | ------------------------------------------------------------------------------- | ------- | | `initial_reference_point` | `Optional[ndarray]` | User-specified initial reference point. Must be between ideal and nadir points. | `None` | Returns: | Type | Description | | --------- | ------------------------------------------ | | `ndarray` | np.ndarray: Valid initial reference point. | Raises: | Type | Description | | ------------ | ----------------------------------------------------------- | | `ValueError` | If the provided reference point is outside the valid range. | Source code in `desdeo/adm/adm_chen.py` ``` def generate_initial_preference(self, initial_reference_point: np.ndarray | None = None) -> np.ndarray: """Generate the initial reference point for the ADM. If an initial reference point is provided, it validates that the point lies between the ideal and nadir points. Otherwise, generates a random point within the feasible objective space. Args: initial_reference_point (Optional[np.ndarray]): User-specified initial reference point. Must be between ideal and nadir points. Returns: np.ndarray: Valid initial reference point. Raises: ValueError: If the provided reference point is outside the valid range. """ if initial_reference_point is not None: if not (self.true_ideal <= initial_reference_point <= self.true_nadir).all(): raise ValueError("Initial reference point must be between the ideal and nadir points.") return initial_reference_point # Generate random reference point between ideal and nadir return np.array( [ self.rng.uniform(min_val, max_val) for min_val, max_val in zip( self.problem.get_ideal_point().values(), self.problem.get_nadir_point().values(), strict=True, ) ] ) ``` ##### generate_preference_decision ``` generate_preference_decision(front: ndarray) -> np.ndarray ``` Generate preference during the decision phase by selecting the best solution. In the decision phase, the ADM acts more decisively by evaluating all solutions in the current front using the utility function and selecting the one with minimum disutility (best utility value). This represents the final decision-making behavior after the learning phase. Parameters: | Name | Type | Description | Default | | ------- | --------- | ------------------------------------------------------------ | ---------- | | `front` | `ndarray` | Current Pareto front with shape (n_solutions, n_objectives). | *required* | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: The solution with minimum disutility as the preferred reference point. | Note The returned solution represents the ADM's final preference and should be close to the decision maker's most preferred solution. Source code in `desdeo/adm/adm_chen.py` ``` def generate_preference_decision(self, front: np.ndarray) -> np.ndarray: """Generate preference during the decision phase by selecting the best solution. In the decision phase, the ADM acts more decisively by evaluating all solutions in the current front using the utility function and selecting the one with minimum disutility (best utility value). This represents the final decision-making behavior after the learning phase. Args: front (np.ndarray): Current Pareto front with shape (n_solutions, n_objectives). Returns: np.ndarray: The solution with minimum disutility as the preferred reference point. Note: The returned solution represents the ADM's final preference and should be close to the decision maker's most preferred solution. """ min_disutility = np.inf preferred_solution = None # Evaluate all solutions and find the one with minimum disutility for solution in front: disutility = self.utility_function(solution, self.true_ideal, self.true_nadir, self.weights) if disutility < min_disutility: min_disutility = disutility preferred_solution = solution return preferred_solution ``` ##### generate_preference_learning ``` generate_preference_learning(front: ndarray) -> np.ndarray ``` Generate preference during the learning phase through systematic exploration. The learning phase explores the Pareto front by identifying neighboring solution pairs with the maximum normalized Euclidean distance. Parameters: | Name | Type | Description | Default | | ------- | --------- | ------------------------------------------------------------ | ---------- | | `front` | `ndarray` | Current Pareto front with shape (n_solutions, n_objectives). | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------------------ | | `ndarray` | np.ndarray: New reference point derived from the most distant neighbors. | Note The reference point is set as the componentwise minimum of the most distant neighboring pair, which represents an aspirational point that is better than both neighbors in all objectives. Todo Validate that the same region has not been selected before to avoid redundant exploration. Source code in `desdeo/adm/adm_chen.py` ``` def generate_preference_learning(self, front: np.ndarray) -> np.ndarray: """Generate preference during the learning phase through systematic exploration. The learning phase explores the Pareto front by identifying neighboring solution pairs with the maximum normalized Euclidean distance. Args: front (np.ndarray): Current Pareto front with shape (n_solutions, n_objectives). Returns: np.ndarray: New reference point derived from the most distant neighbors. Note: The reference point is set as the componentwise minimum of the most distant neighboring pair, which represents an aspirational point that is better than both neighbors in all objectives. Todo: Validate that the same region has not been selected before to avoid redundant exploration. """ # Extend front with extreme solutions for comprehensive exploration extended_set = np.append(front, self.extreme_solutions, axis=0) neighbors_1 = [] neighbors_2 = [] euclidean_distances = [] # Find all neighboring pairs and compute their distances for i in range(extended_set.shape[0] - 1): z1 = extended_set[i, :] for j in range(i + 1, extended_set.shape[0]): z2 = extended_set[j, :] if self.are_neighbors(z1, z2, extended_set): neighbors_1.append(z1) neighbors_2.append(z2) euclidean_distances.append( self.normalized_euclidean_distance(z1, z2, self.true_nadir, self.true_ideal) ) # Select the pair with maximum distance for exploration max_distance_idx = np.argmax(euclidean_distances) # Generate reference point as componentwise minimum of the distant pair return np.minimum(neighbors_1[max_distance_idx], neighbors_2[max_distance_idx]) ``` ##### get_extreme_solutions ``` get_extreme_solutions(front: ndarray) -> np.ndarray ``` Extract extreme solutions from the Pareto front. An extreme solution is defined as the objective vector that minimizes one of the objective functions on the Pareto front. These solutions represent the boundaries of the achievable objective space. Parameters: | Name | Type | Description | Default | | ------- | --------- | ---------------------------------------------------- | ---------- | | `front` | `ndarray` | Pareto front with shape (n_solutions, n_objectives). | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `ndarray` | np.ndarray: Array of extreme solutions with shape (n_objectives, n_objectives). Each row represents an extreme solution for one objective. | Example For a 2-objective problem with front = \[[1, 3], [2, 2], [3, 1]\]: - Extreme for obj 1: [1, 3] (min value 1 in first objective) - Extreme for obj 2: [3, 1] (min value 1 in second objective) Source code in `desdeo/adm/adm_chen.py` ``` def get_extreme_solutions(self, front: np.ndarray) -> np.ndarray: """Extract extreme solutions from the Pareto front. An extreme solution is defined as the objective vector that minimizes one of the objective functions on the Pareto front. These solutions represent the boundaries of the achievable objective space. Args: front (np.ndarray): Pareto front with shape (n_solutions, n_objectives). Returns: np.ndarray: Array of extreme solutions with shape (n_objectives, n_objectives). Each row represents an extreme solution for one objective. Example: For a 2-objective problem with front = [[1, 3], [2, 2], [3, 1]]: - Extreme for obj 1: [1, 3] (min value 1 in first objective) - Extreme for obj 2: [3, 1] (min value 1 in second objective) """ extreme_solutions = [] for i in range(front.shape[1]): # For each objective idx_min_i = np.argmin(front[:, i]) # Find solution with minimum value extreme_solutions.append(front[idx_min_i]) return np.array(extreme_solutions) ``` ##### get_next_preference ``` get_next_preference(front: ndarray) -> np.ndarray ``` Get the next preference (reference point) based on the current iteration phase. This method determines whether the ADM is in the learning or decision phase and calls the appropriate preference generation method. Parameters: | Name | Type | Description | Default | | ------- | --------- | -------------------------------------------------------------------------- | ---------- | | `front` | `ndarray` | Current Pareto front approximation with shape (n_solutions, n_objectives). | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------ | | `ndarray` | np.ndarray: Next reference point for the interactive method. | Source code in `desdeo/adm/adm_chen.py` ``` def get_next_preference(self, front: np.ndarray) -> np.ndarray: """Get the next preference (reference point) based on the current iteration phase. This method determines whether the ADM is in the learning or decision phase and calls the appropriate preference generation method. Args: front (np.ndarray): Current Pareto front approximation with shape (n_solutions, n_objectives). Returns: np.ndarray: Next reference point for the interactive method. """ if self.iteration_counter < self.it_learning_phase: self.preference = self.generate_preference_learning(front) else: self.preference = self.generate_preference_decision(front) self.iteration_counter += 1 return self.preference ``` ##### normalized_euclidean_distance ``` normalized_euclidean_distance( za: ndarray, zb: ndarray, znad: ndarray, zstar: ndarray, eps: float | None = None, ) -> float ``` Compute normalized Euclidean distance between two solutions. The normalization is performed using the range between the utopian point (ideal - eps) and the nadir point. This ensures that the distance metric is scale-independent across different objectives. Parameters: | Name | Type | Description | Default | | ------- | ----------------- | ----------------------------------------------------------------- | ---------- | | `za` | `ndarray` | First solution vector of shape (n_objectives,). | *required* | | `zb` | `ndarray` | Second solution vector of shape (n_objectives,). | *required* | | `znad` | `ndarray` | Nadir point (worst values) of shape (n_objectives,). | *required* | | `zstar` | `ndarray` | Ideal point (best values) of shape (n_objectives,). | *required* | | `eps` | `Optional[float]` | Small positive value for utopian shift. Defaults to 1e-6 if None. | `None` | Returns: | Name | Type | Description | | ------- | ------- | ------------------------------------------------ | | `float` | `float` | Normalized Euclidean distance between za and zb. | Note The utopian point is computed as zstar - eps to ensure strict improvement over the ideal point. Division by zero is avoided by replacing zero denominators with 1e-12. Source code in `desdeo/adm/adm_chen.py` ``` @staticmethod def normalized_euclidean_distance( za: np.ndarray, zb: np.ndarray, znad: np.ndarray, zstar: np.ndarray, eps: float | None = None ) -> float: """Compute normalized Euclidean distance between two solutions. The normalization is performed using the range between the utopian point (ideal - eps) and the nadir point. This ensures that the distance metric is scale-independent across different objectives. Args: za (np.ndarray): First solution vector of shape (n_objectives,). zb (np.ndarray): Second solution vector of shape (n_objectives,). znad (np.ndarray): Nadir point (worst values) of shape (n_objectives,). zstar (np.ndarray): Ideal point (best values) of shape (n_objectives,). eps (Optional[float]): Small positive value for utopian shift. Defaults to 1e-6 if None. Returns: float: Normalized Euclidean distance between za and zb. Note: The utopian point is computed as zstar - eps to ensure strict improvement over the ideal point. Division by zero is avoided by replacing zero denominators with 1e-12. """ za, zb, znad, zstar = map(np.asarray, (za, zb, znad, zstar)) if eps is None: eps = 1e-6 if np.isscalar(eps): eps = np.full_like(zstar, eps, dtype=float) # Compute utopian point (strictly better than ideal) z_utopian = zstar - eps # Compute normalization denominator denom = znad - z_utopian # Avoid division by zero when nadir ≈ utopian denom = np.where(denom <= 0, 1e-12, denom) # Compute normalized difference and Euclidean distance diff = (za - zb) / denom return np.sqrt(np.sum(diff**2)) ``` ##### utility_function ``` utility_function( z: ndarray, zstar: ndarray, znad: ndarray, weight: ndarray, utility_type: str = "deterministic", eps: float | None = None, ) -> float ``` Compute the utility function value for a given solution. The utility function measures the maximum weighted normalized distance from the utopian point. Lower values indicate better solutions. Parameters: | Name | Type | Description | Default | | -------------- | --------- | ------------------------------------------------------------------------------------------ | --------------------------------------------------------- | | `z` | `ndarray` | Solution vector of shape (n_objectives,). | *required* | | `zstar` | `ndarray` | Ideal point of shape (n_objectives,). | *required* | | `znad` | `ndarray` | Nadir point of shape (n_objectives,). | *required* | | `weight` | `ndarray` | Objective weights of shape (n_objectives,). | *required* | | `utility_type` | `str` | Type of utility function. Options: 'deterministic', 'random'. Defaults to 'deterministic'. | `'deterministic'` | | `eps` | \`float | None\` | Small positive value for utopian shift. Defaults to 1e-6. | Returns: | Name | Type | Description | | ------- | ------- | ----------------------------------------- | | `float` | `float` | Utility function value (lower is better). | Note When utility_type='random', Gaussian noise is added with standard deviation that decreases over iterations to simulate learning behavior. The noise magnitude is based on the utility function range. Source code in `desdeo/adm/adm_chen.py` ``` def utility_function( self, z: np.ndarray, zstar: np.ndarray, znad: np.ndarray, weight: np.ndarray, utility_type: str = "deterministic", eps: float | None = None, ) -> float: """Compute the utility function value for a given solution. The utility function measures the maximum weighted normalized distance from the utopian point. Lower values indicate better solutions. Args: z (np.ndarray): Solution vector of shape (n_objectives,). zstar (np.ndarray): Ideal point of shape (n_objectives,). znad (np.ndarray): Nadir point of shape (n_objectives,). weight (np.ndarray): Objective weights of shape (n_objectives,). utility_type (str): Type of utility function. Options: 'deterministic', 'random'. Defaults to 'deterministic'. eps (float | None): Small positive value for utopian shift. Defaults to 1e-6. Returns: float: Utility function value (lower is better). Note: When utility_type='random', Gaussian noise is added with standard deviation that decreases over iterations to simulate learning behavior. The noise magnitude is based on the utility function range. """ z, znad, zstar, weight = map(np.asarray, (z, znad, zstar, weight)) if eps is None: eps = 1e-6 if np.isscalar(eps): eps = np.full_like(zstar, eps, dtype=float) # Compute utopian point (strictly better than ideal) z_utopian = zstar - eps # Compute normalization denominator denom = znad - z_utopian # Avoid division by zero denom = np.where(denom <= 0, 1e-12, denom) # Compute weighted normalized distances diff = weight * ((z - z_utopian) / denom) u_minus = np.max(diff) # Chebyshev scalarization # Add random component if requested if utility_type == "random": # Noise decreases over iterations to simulate learning sigma = (self.UF_max - self.UF_opt) * 0.2 / (2 ** (self.it_decision_phase - 1)) noise = self.rng.uniform(low=0, high=sigma) u_minus = noise + u_minus return u_minus ``` ### desdeo.adm.adm_afsar Artificial decision maker (ADM) based on the approach by Afsar et al. #### ADMAfsar Bases: `BaseADM` Adaptive Decision Maker using the AFSAR approach. This ADM generates preferences for interactive evolutionary multiobjective optimization based on the method described in: > Afsar, B., Miettinen, K., & Ruiz, A. B. (2021). An Artificial Decision Maker for Comparing Reference Point Based Interactive Evolutionary Multiobjective Optimization Methods. In: Ishibuchi, H., et al. Evolutionary Multi-Criterion Optimization. EMO 2021. Lecture Notes in Computer Science, vol 12654. Springer, Cham. > > Afsar, B., Ruiz, A. B., & Miettinen, K. (2023). Comparing interactive evolutionary multiobjective optimization methods with an artificial decision maker. Complex & Intelligent Systems, Volume 9, pages 1165-1181. Springer. Attributes: | Name | Type | Description | | --------------------- | ------------- | -------------------------------------------------------- | | `composite_front` | `list` | Stores the composite front of solutions. | | `max_assigned_vector` | `int or None` | Index of the vector with the maximum assigned solutions. | | `reference_vectors` | `ndarray` | Array of reference vectors. | | `preference` | `dict` | Current preference information. | Source code in `desdeo/adm/adm_afsar.py` ``` class ADMAfsar(BaseADM): """Adaptive Decision Maker using the AFSAR approach. This ADM generates preferences for interactive evolutionary multiobjective optimization based on the method described in: > Afsar, B., Miettinen, K., & Ruiz, A. B. (2021). An Artificial Decision Maker > for Comparing Reference Point Based Interactive Evolutionary Multiobjective > Optimization Methods. In: Ishibuchi, H., et al. Evolutionary Multi-Criterion > Optimization. EMO 2021. Lecture Notes in Computer Science, vol 12654. > Springer, Cham. > Afsar, B., Ruiz, A. B., & Miettinen, K. (2023). > Comparing interactive evolutionary multiobjective optimization methods with an artificial decision maker. > Complex & Intelligent Systems, Volume 9, pages 1165-1181. Springer. Attributes: composite_front (list): Stores the composite front of solutions. max_assigned_vector (int or None): Index of the vector with the maximum assigned solutions. reference_vectors (np.ndarray): Array of reference vectors. preference (dict): Current preference information. """ def __init__( self, problem: Problem, it_learning_phase: int, it_decision_phase: int, lattice_resolution: int | None = None, number_of_vectors: int | None = None, seed: int | None = None, ): """Initialize the artificial decision maker proposed by Afsar et al. Args: problem (Problem): The optimization problem to solve. it_learning_phase (int): Number of iterations for the learning phase. it_decision_phase (int): Number of iterations for the decision phase. lattice_resolution (int, optional): Lattice resolution for reference vectors. number_of_vectors (int, optional): Number of reference vectors. seed (int | None): Optional seed for the random number generator. Defaults to None. """ self.true_ideal, self.true_nadir = payoff_table_method(problem) problem = problem.update_ideal_and_nadir(new_ideal=self.true_ideal, new_nadir=self.true_nadir) super().__init__(problem, it_learning_phase, it_decision_phase, seed=seed) self.composite_front = [] self.max_assigned_vector = None self.preference_type = "reference_point" number_of_objectives = len(problem.objectives) self.reference_vectors = create_simplex(number_of_objectives, lattice_resolution, number_of_vectors) self.true_ideal, self.true_nadir = payoff_table_method(problem) self.generate_initial_preference() def generate_initial_preference(self): """Generate the initial preference as a random point between the ideal and nadir points. The preference is stored in self.preference as a numpy array. """ self.preference = np.array( [ self.rng.uniform(min_val, max_val) for min_val, max_val in zip( self.problem.get_ideal_point().values(), self.problem.get_nadir_point().values(), strict=True, ) ] ) def get_next_preference(self, *fronts: np.ndarray, preference_type: str = "reference_point") -> np.ndarray: """Generate the next preference based on the current phase and provided solution fronts. Args: *fronts: One or more solution fronts (arrays) to be considered. preference_type (str): The type of preference to generate. Returns: np.ndarray: The generated preference information. """ self.preference_type = preference_type if len(self.composite_front) == 0: self.composite_front = self.generate_composite_front(*fronts) else: self.composite_front = self.generate_composite_front(self.composite_front, *fronts) ideal_point = self.composite_front.min(axis=0) translated_front = self.translate_front(self.composite_front, ideal_point) normalized_front = self.normalize_front(self.composite_front, translated_front) assigned_vectors = self.assign_vectors(normalized_front) if self.iteration_counter < self.it_learning_phase: self.preference = self.generate_preference_learning(ideal_point, translated_front, assigned_vectors) else: if self.iteration_counter == self.it_learning_phase: self.max_assigned_vector = self.get_max_assigned_vector(assigned_vectors) self.preference = self.generate_preference_decision( ideal_point, translated_front, assigned_vectors, self.max_assigned_vector, ) self.iteration_counter += 1 return self.preference def assign_vectors(self, front) -> np.ndarray: """Assign each solution in the front to the closest reference vector using cosine similarity. Args: front (np.ndarray): The normalized solution front. Returns: np.ndarray: Indices of the assigned reference vectors for each solution. """ cosine = np.dot(front, np.transpose(self.reference_vectors)) if cosine[np.where(cosine > 1)].size: cosine[np.where(cosine > 1)] = 1 if cosine[np.where(cosine < 0)].size: cosine[np.where(cosine < 0)] = 0 return np.argmax(cosine, axis=1) def normalize_front(self, front, translated_front) -> np.ndarray: """Normalize the translated front so that each solution has unit length. Args: front (np.ndarray): The original solution front. translated_front (np.ndarray): The translated solution front. Returns: np.ndarray: The normalized solution front. """ translated_norm = np.linalg.norm(translated_front, axis=1) translated_norm = np.repeat(translated_norm, len(translated_front[0, :])).reshape(len(front), len(front[0, :])) translated_norm[translated_norm == 0] = np.finfo(float).eps return np.divide(translated_front, translated_norm) def generate_composite_front(self, *fronts: np.ndarray) -> np.ndarray: """Generate the composite front by stacking and extracting the non-dominated solutions. Args: *fronts: One or more solution fronts (arrays). Returns: np.ndarray: The composite non-dominated front. """ _fronts = np.vstack(fronts) return _fronts[nds(_fronts)] def translate_front(self, front, ideal) -> np.ndarray: """Translate the front by subtracting the ideal point from each solution. Args: front (np.ndarray): The solution front. ideal (np.ndarray): The ideal point. Returns: np.ndarray: The translated front. """ return np.subtract(front, ideal) def generate_preference_learning(self, ideal_point, translated_front, assigned_vectors) -> np.ndarray: """Generate preference information during the learning phase. The preference is generated according to the selected preference type: - 'reference_point': Returns a reference point. - 'preferred_ranges': Returns a preferred range. - 'preferred_solutions': Returns preferred solutions. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.ndarray: The generated preference information. """ if self.preference_type == "reference_point": return self.generate_reference_point_learning(ideal_point, translated_front, assigned_vectors) if self.preference_type == "preferred_ranges": return self.generate_ranges_learning(ideal_point, translated_front, assigned_vectors) if self.preference_type == "preferred_solutions": return self.generate_preferred_solutions_learning(ideal_point, translated_front, assigned_vectors) raise ValueError( f"Invalid preference type: {self.preference_type}. " "Valid options are 'reference_point', 'preferred_ranges', " "'preferred_solutions', or 'non_preferred_solutions'." ) def generate_preference_decision( self, ideal_point, translated_front, assigned_vectors, max_assigned_vector ) -> np.ndarray: """Generate preference information during the decision phase. The preference is generated according to the selected preference type: - 'reference_point': Returns a reference point. - 'preferred_ranges': Returns a preferred range. - 'preferred_solutions': Returns preferred solutions. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. max_assigned_vector (int): Index of the reference vector with the maximum assigned solutions. Returns: np.ndarray: The generated preference information. """ if self.preference_type == "reference_point": return self.generate_reference_point_decision( ideal_point, translated_front, assigned_vectors, max_assigned_vector, ) if self.preference_type == "preferred_ranges": return self.generate_ranges_decision(ideal_point, translated_front, assigned_vectors, max_assigned_vector) if self.preference_type == "preferred_solutions": return self.generate_preferred_solutions_decision( ideal_point, translated_front, assigned_vectors, max_assigned_vector ) raise ValueError( f"Invalid preference type: {self.preference_type}. " "Valid options are 'reference_point', 'preferred_ranges', " "'preferred_solutions', or 'non_preferred_solutions'." ) def get_max_assigned_vector(self, assigned_vectors) -> np.ndarray: """Find the reference vector with the maximum number of assigned solutions. Args: assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.ndarray: Indices of the reference vector(s) with the maximum assignments. """ number_assigned = np.bincount(assigned_vectors) return np.atleast_1d( np.squeeze(np.where(number_assigned == np.max(number_assigned[np.nonzero(number_assigned)]))) ) def generate_reference_point_learning(self, ideal_point, translated_front, assigned_vectors) -> np.ndarray: """Generate a reference point for the learning phase. The reference point is based on the solution assigned to the reference vector with the minimum number of assigned solutions and closest to the origin. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.array: The generated reference point. """ ideal_cf = ideal_point translated_cf = translated_front number_assigned = np.bincount(assigned_vectors) min_assigned_vector = np.atleast_1d( np.squeeze(np.where(number_assigned == np.min(number_assigned[np.nonzero(number_assigned)]))) ) sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == min_assigned_vector[0]))) sub_population_fitness = translated_cf[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.where(sub_pop_fitness_magnitude == np.nanmin(sub_pop_fitness_magnitude)) distance_selected = sub_pop_fitness_magnitude[minidx] reference_point = distance_selected[0] * self.reference_vectors[min_assigned_vector[0]] return np.squeeze(reference_point + ideal_cf) def generate_reference_point_decision( self, ideal_point, translated_front, assigned_vectors, max_assigned_vector ) -> np.ndarray: """Generate a reference point for the decision phase. The reference point is based on the solution assigned to the reference vector with the maximum number of assigned solutions and closest to the origin. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. max_assigned_vector (int): Index of the reference vector with the maximum assigned solutions. Returns: np.ndarray: The generated reference point. """ ideal_cf = ideal_point translated_cf = translated_front sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == max_assigned_vector))) sub_population_fitness = translated_cf[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.where(sub_pop_fitness_magnitude == np.nanmin(sub_pop_fitness_magnitude)) distance_selected = sub_pop_fitness_magnitude[minidx] reference_point = distance_selected[0] * self.reference_vectors[max_assigned_vector] return np.squeeze(reference_point + ideal_cf) def generate_ranges_learning(self, ideal_point, translated_front, assigned_vectors) -> np.ndarray: """Generate the preferred ranges for the learning phase. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.ndarray: an array of ranges. """ number_assigned = np.bincount(assigned_vectors) min_assigned_vector = np.atleast_1d( np.squeeze(np.where(number_assigned == np.min(number_assigned[np.nonzero(number_assigned)]))) ) sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == min_assigned_vector[0]))) sub_population_fitness = translated_front[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.where(sub_pop_fitness_magnitude == np.nanmin(sub_pop_fitness_magnitude)) distance_selected = sub_pop_fitness_magnitude[minidx] reference_point = distance_selected[0] * self.reference_vectors[min_assigned_vector[0]] distance = min(np.linalg.norm(reference_point - i) for i in sub_population_fitness) reference_point = np.squeeze(reference_point + ideal_point) temp = reference_point - distance temp2 = reference_point + distance true_ideal = np.array(list(self.problem.get_ideal_point().values())) true_nadir = np.array(list(self.problem.get_nadir_point().values())) for i in range(reference_point.shape[0]): reference_point[i] = max(reference_point[i], true_ideal[i]) reference_point[i] = min(reference_point[i], true_nadir[i]) temp[i] = max(temp[i], true_ideal[i]) temp[i] = min(temp[i], true_nadir[i]) temp2[i] = max(temp2[i], true_ideal[i]) temp2[i] = min(temp2[i], true_nadir[i]) # TODO (giomara): return the reference point in some other place return np.vstack((temp, temp2)).T def generate_ranges_decision( self, ideal_point, translated_front, assigned_vectors, max_assigned_vector ) -> np.ndarray: """Generate the preferred ranges for the decision phase. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. max_assigned_vector (int): Index of the reference vector with the maximum assigned solutions. Returns: np.ndarray: an array of ranges. """ sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == max_assigned_vector))) sub_population_fitness = translated_front[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.where(sub_pop_fitness_magnitude == np.nanmin(sub_pop_fitness_magnitude)) distance_selected = sub_pop_fitness_magnitude[minidx] reference_point = distance_selected[0] * self.reference_vectors[max_assigned_vector] distance = min(np.linalg.norm(reference_point - i) for i in sub_population_fitness) reference_point = np.squeeze(reference_point + ideal_point) reference_point = np.squeeze(reference_point - distance) temp = reference_point - distance temp2 = reference_point + distance true_ideal = np.array(list(self.problem.get_ideal_point().values())) true_nadir = np.array(list(self.problem.get_nadir_point().values())) for i in range(reference_point.shape[0]): reference_point[i] = max(reference_point[i], true_ideal[i]) reference_point[i] = min(reference_point[i], true_nadir[i]) temp[i] = max(temp[i], true_ideal[i]) temp[i] = min(temp[i], true_nadir[i]) temp2[i] = max(temp2[i], true_ideal[i]) temp2[i] = min(temp2[i], true_nadir[i]) return np.vstack((temp, temp2)).T def generate_preferred_solutions_learning(self, ideal_point, translated_front, assigned_vectors) -> np.ndarray: """Generate the preferred solutions during the learning phase. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.ndarray: The preferred solutions. """ number_assigned = np.bincount(assigned_vectors) min_assigned_vector = np.atleast_1d( np.squeeze(np.where(number_assigned == np.min(number_assigned[np.nonzero(number_assigned)]))) ) sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == min_assigned_vector[0]))) sub_population_fitness = translated_front[sub_population_index] return np.squeeze(sub_population_fitness + ideal_point) def generate_preferred_solutions_decision( self, ideal_point, translated_front, assigned_vectors, max_assigned_vector ) -> np.ndarray: """Generate the preferred solutions during the decision phase. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. max_assigned_vector (int): Index of the reference vector with the maximum assigned solutions. Returns: np.ndarray: The preferred solutions. """ sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == max_assigned_vector))) sub_population_fitness = translated_front[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.argpartition(sub_pop_fitness_magnitude, 4) solution_selected = sub_population_fitness[minidx[:4]] return np.squeeze(solution_selected + ideal_point) ``` ##### __init__ ``` __init__( problem: Problem, it_learning_phase: int, it_decision_phase: int, lattice_resolution: int | None = None, number_of_vectors: int | None = None, seed: int | None = None, ) ``` Initialize the artificial decision maker proposed by Afsar et al. Parameters: | Name | Type | Description | Default | | -------------------- | --------- | -------------------------------------------- | ---------------------------------------------------------------- | | `problem` | `Problem` | The optimization problem to solve. | *required* | | `it_learning_phase` | `int` | Number of iterations for the learning phase. | *required* | | `it_decision_phase` | `int` | Number of iterations for the decision phase. | *required* | | `lattice_resolution` | `int` | Lattice resolution for reference vectors. | `None` | | `number_of_vectors` | `int` | Number of reference vectors. | `None` | | `seed` | \`int | None\` | Optional seed for the random number generator. Defaults to None. | Source code in `desdeo/adm/adm_afsar.py` ``` def __init__( self, problem: Problem, it_learning_phase: int, it_decision_phase: int, lattice_resolution: int | None = None, number_of_vectors: int | None = None, seed: int | None = None, ): """Initialize the artificial decision maker proposed by Afsar et al. Args: problem (Problem): The optimization problem to solve. it_learning_phase (int): Number of iterations for the learning phase. it_decision_phase (int): Number of iterations for the decision phase. lattice_resolution (int, optional): Lattice resolution for reference vectors. number_of_vectors (int, optional): Number of reference vectors. seed (int | None): Optional seed for the random number generator. Defaults to None. """ self.true_ideal, self.true_nadir = payoff_table_method(problem) problem = problem.update_ideal_and_nadir(new_ideal=self.true_ideal, new_nadir=self.true_nadir) super().__init__(problem, it_learning_phase, it_decision_phase, seed=seed) self.composite_front = [] self.max_assigned_vector = None self.preference_type = "reference_point" number_of_objectives = len(problem.objectives) self.reference_vectors = create_simplex(number_of_objectives, lattice_resolution, number_of_vectors) self.true_ideal, self.true_nadir = payoff_table_method(problem) self.generate_initial_preference() ``` ##### assign_vectors ``` assign_vectors(front) -> np.ndarray ``` Assign each solution in the front to the closest reference vector using cosine similarity. Parameters: | Name | Type | Description | Default | | ------- | --------- | ------------------------------ | ---------- | | `front` | `ndarray` | The normalized solution front. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------------------ | | `ndarray` | np.ndarray: Indices of the assigned reference vectors for each solution. | Source code in `desdeo/adm/adm_afsar.py` ``` def assign_vectors(self, front) -> np.ndarray: """Assign each solution in the front to the closest reference vector using cosine similarity. Args: front (np.ndarray): The normalized solution front. Returns: np.ndarray: Indices of the assigned reference vectors for each solution. """ cosine = np.dot(front, np.transpose(self.reference_vectors)) if cosine[np.where(cosine > 1)].size: cosine[np.where(cosine > 1)] = 1 if cosine[np.where(cosine < 0)].size: cosine[np.where(cosine < 0)] = 0 return np.argmax(cosine, axis=1) ``` ##### generate_composite_front ``` generate_composite_front(*fronts: ndarray) -> np.ndarray ``` Generate the composite front by stacking and extracting the non-dominated solutions. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------------------- | ------- | | `*fronts` | `ndarray` | One or more solution fronts (arrays). | `()` | Returns: | Type | Description | | --------- | ---------------------------------------------- | | `ndarray` | np.ndarray: The composite non-dominated front. | Source code in `desdeo/adm/adm_afsar.py` ``` def generate_composite_front(self, *fronts: np.ndarray) -> np.ndarray: """Generate the composite front by stacking and extracting the non-dominated solutions. Args: *fronts: One or more solution fronts (arrays). Returns: np.ndarray: The composite non-dominated front. """ _fronts = np.vstack(fronts) return _fronts[nds(_fronts)] ``` ##### generate_initial_preference ``` generate_initial_preference() ``` Generate the initial preference as a random point between the ideal and nadir points. The preference is stored in self.preference as a numpy array. Source code in `desdeo/adm/adm_afsar.py` ``` def generate_initial_preference(self): """Generate the initial preference as a random point between the ideal and nadir points. The preference is stored in self.preference as a numpy array. """ self.preference = np.array( [ self.rng.uniform(min_val, max_val) for min_val, max_val in zip( self.problem.get_ideal_point().values(), self.problem.get_nadir_point().values(), strict=True, ) ] ) ``` ##### generate_preference_decision ``` generate_preference_decision( ideal_point, translated_front, assigned_vectors, max_assigned_vector, ) -> np.ndarray ``` Generate preference information during the decision phase. The preference is generated according to the selected preference type: - 'reference_point': Returns a reference point. - 'preferred_ranges': Returns a preferred range. - 'preferred_solutions': Returns preferred solutions. Parameters: | Name | Type | Description | Default | | --------------------- | --------- | ------------------------------------------------------------------ | ---------- | | `ideal_point` | `ndarray` | The ideal point. | *required* | | `translated_front` | `ndarray` | The translated solution front. | *required* | | `assigned_vectors` | `ndarray` | Indices of assigned reference vectors. | *required* | | `max_assigned_vector` | `int` | Index of the reference vector with the maximum assigned solutions. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------- | | `ndarray` | np.ndarray: The generated preference information. | Source code in `desdeo/adm/adm_afsar.py` ``` def generate_preference_decision( self, ideal_point, translated_front, assigned_vectors, max_assigned_vector ) -> np.ndarray: """Generate preference information during the decision phase. The preference is generated according to the selected preference type: - 'reference_point': Returns a reference point. - 'preferred_ranges': Returns a preferred range. - 'preferred_solutions': Returns preferred solutions. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. max_assigned_vector (int): Index of the reference vector with the maximum assigned solutions. Returns: np.ndarray: The generated preference information. """ if self.preference_type == "reference_point": return self.generate_reference_point_decision( ideal_point, translated_front, assigned_vectors, max_assigned_vector, ) if self.preference_type == "preferred_ranges": return self.generate_ranges_decision(ideal_point, translated_front, assigned_vectors, max_assigned_vector) if self.preference_type == "preferred_solutions": return self.generate_preferred_solutions_decision( ideal_point, translated_front, assigned_vectors, max_assigned_vector ) raise ValueError( f"Invalid preference type: {self.preference_type}. " "Valid options are 'reference_point', 'preferred_ranges', " "'preferred_solutions', or 'non_preferred_solutions'." ) ``` ##### generate_preference_learning ``` generate_preference_learning( ideal_point, translated_front, assigned_vectors ) -> np.ndarray ``` Generate preference information during the learning phase. The preference is generated according to the selected preference type: - 'reference_point': Returns a reference point. - 'preferred_ranges': Returns a preferred range. - 'preferred_solutions': Returns preferred solutions. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | -------------------------------------- | ---------- | | `ideal_point` | `ndarray` | The ideal point. | *required* | | `translated_front` | `ndarray` | The translated solution front. | *required* | | `assigned_vectors` | `ndarray` | Indices of assigned reference vectors. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------- | | `ndarray` | np.ndarray: The generated preference information. | Source code in `desdeo/adm/adm_afsar.py` ``` def generate_preference_learning(self, ideal_point, translated_front, assigned_vectors) -> np.ndarray: """Generate preference information during the learning phase. The preference is generated according to the selected preference type: - 'reference_point': Returns a reference point. - 'preferred_ranges': Returns a preferred range. - 'preferred_solutions': Returns preferred solutions. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.ndarray: The generated preference information. """ if self.preference_type == "reference_point": return self.generate_reference_point_learning(ideal_point, translated_front, assigned_vectors) if self.preference_type == "preferred_ranges": return self.generate_ranges_learning(ideal_point, translated_front, assigned_vectors) if self.preference_type == "preferred_solutions": return self.generate_preferred_solutions_learning(ideal_point, translated_front, assigned_vectors) raise ValueError( f"Invalid preference type: {self.preference_type}. " "Valid options are 'reference_point', 'preferred_ranges', " "'preferred_solutions', or 'non_preferred_solutions'." ) ``` ##### generate_preferred_solutions_decision ``` generate_preferred_solutions_decision( ideal_point, translated_front, assigned_vectors, max_assigned_vector, ) -> np.ndarray ``` Generate the preferred solutions during the decision phase. Parameters: | Name | Type | Description | Default | | --------------------- | --------- | ------------------------------------------------------------------ | ---------- | | `ideal_point` | `ndarray` | The ideal point. | *required* | | `translated_front` | `ndarray` | The translated solution front. | *required* | | `assigned_vectors` | `ndarray` | Indices of assigned reference vectors. | *required* | | `max_assigned_vector` | `int` | Index of the reference vector with the maximum assigned solutions. | *required* | Returns: | Type | Description | | --------- | ------------------------------------ | | `ndarray` | np.ndarray: The preferred solutions. | Source code in `desdeo/adm/adm_afsar.py` ``` def generate_preferred_solutions_decision( self, ideal_point, translated_front, assigned_vectors, max_assigned_vector ) -> np.ndarray: """Generate the preferred solutions during the decision phase. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. max_assigned_vector (int): Index of the reference vector with the maximum assigned solutions. Returns: np.ndarray: The preferred solutions. """ sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == max_assigned_vector))) sub_population_fitness = translated_front[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.argpartition(sub_pop_fitness_magnitude, 4) solution_selected = sub_population_fitness[minidx[:4]] return np.squeeze(solution_selected + ideal_point) ``` ##### generate_preferred_solutions_learning ``` generate_preferred_solutions_learning( ideal_point, translated_front, assigned_vectors ) -> np.ndarray ``` Generate the preferred solutions during the learning phase. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | -------------------------------------- | ---------- | | `ideal_point` | `ndarray` | The ideal point. | *required* | | `translated_front` | `ndarray` | The translated solution front. | *required* | | `assigned_vectors` | `ndarray` | Indices of assigned reference vectors. | *required* | Returns: | Type | Description | | --------- | ------------------------------------ | | `ndarray` | np.ndarray: The preferred solutions. | Source code in `desdeo/adm/adm_afsar.py` ``` def generate_preferred_solutions_learning(self, ideal_point, translated_front, assigned_vectors) -> np.ndarray: """Generate the preferred solutions during the learning phase. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.ndarray: The preferred solutions. """ number_assigned = np.bincount(assigned_vectors) min_assigned_vector = np.atleast_1d( np.squeeze(np.where(number_assigned == np.min(number_assigned[np.nonzero(number_assigned)]))) ) sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == min_assigned_vector[0]))) sub_population_fitness = translated_front[sub_population_index] return np.squeeze(sub_population_fitness + ideal_point) ``` ##### generate_ranges_decision ``` generate_ranges_decision( ideal_point, translated_front, assigned_vectors, max_assigned_vector, ) -> np.ndarray ``` Generate the preferred ranges for the decision phase. Parameters: | Name | Type | Description | Default | | --------------------- | --------- | ------------------------------------------------------------------ | ---------- | | `ideal_point` | `ndarray` | The ideal point. | *required* | | `translated_front` | `ndarray` | The translated solution front. | *required* | | `assigned_vectors` | `ndarray` | Indices of assigned reference vectors. | *required* | | `max_assigned_vector` | `int` | Index of the reference vector with the maximum assigned solutions. | *required* | Returns: | Type | Description | | --------- | ------------------------------- | | `ndarray` | np.ndarray: an array of ranges. | Source code in `desdeo/adm/adm_afsar.py` ``` def generate_ranges_decision( self, ideal_point, translated_front, assigned_vectors, max_assigned_vector ) -> np.ndarray: """Generate the preferred ranges for the decision phase. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. max_assigned_vector (int): Index of the reference vector with the maximum assigned solutions. Returns: np.ndarray: an array of ranges. """ sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == max_assigned_vector))) sub_population_fitness = translated_front[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.where(sub_pop_fitness_magnitude == np.nanmin(sub_pop_fitness_magnitude)) distance_selected = sub_pop_fitness_magnitude[minidx] reference_point = distance_selected[0] * self.reference_vectors[max_assigned_vector] distance = min(np.linalg.norm(reference_point - i) for i in sub_population_fitness) reference_point = np.squeeze(reference_point + ideal_point) reference_point = np.squeeze(reference_point - distance) temp = reference_point - distance temp2 = reference_point + distance true_ideal = np.array(list(self.problem.get_ideal_point().values())) true_nadir = np.array(list(self.problem.get_nadir_point().values())) for i in range(reference_point.shape[0]): reference_point[i] = max(reference_point[i], true_ideal[i]) reference_point[i] = min(reference_point[i], true_nadir[i]) temp[i] = max(temp[i], true_ideal[i]) temp[i] = min(temp[i], true_nadir[i]) temp2[i] = max(temp2[i], true_ideal[i]) temp2[i] = min(temp2[i], true_nadir[i]) return np.vstack((temp, temp2)).T ``` ##### generate_ranges_learning ``` generate_ranges_learning( ideal_point, translated_front, assigned_vectors ) -> np.ndarray ``` Generate the preferred ranges for the learning phase. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | -------------------------------------- | ---------- | | `ideal_point` | `ndarray` | The ideal point. | *required* | | `translated_front` | `ndarray` | The translated solution front. | *required* | | `assigned_vectors` | `ndarray` | Indices of assigned reference vectors. | *required* | Returns: | Type | Description | | --------- | ------------------------------- | | `ndarray` | np.ndarray: an array of ranges. | Source code in `desdeo/adm/adm_afsar.py` ``` def generate_ranges_learning(self, ideal_point, translated_front, assigned_vectors) -> np.ndarray: """Generate the preferred ranges for the learning phase. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.ndarray: an array of ranges. """ number_assigned = np.bincount(assigned_vectors) min_assigned_vector = np.atleast_1d( np.squeeze(np.where(number_assigned == np.min(number_assigned[np.nonzero(number_assigned)]))) ) sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == min_assigned_vector[0]))) sub_population_fitness = translated_front[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.where(sub_pop_fitness_magnitude == np.nanmin(sub_pop_fitness_magnitude)) distance_selected = sub_pop_fitness_magnitude[minidx] reference_point = distance_selected[0] * self.reference_vectors[min_assigned_vector[0]] distance = min(np.linalg.norm(reference_point - i) for i in sub_population_fitness) reference_point = np.squeeze(reference_point + ideal_point) temp = reference_point - distance temp2 = reference_point + distance true_ideal = np.array(list(self.problem.get_ideal_point().values())) true_nadir = np.array(list(self.problem.get_nadir_point().values())) for i in range(reference_point.shape[0]): reference_point[i] = max(reference_point[i], true_ideal[i]) reference_point[i] = min(reference_point[i], true_nadir[i]) temp[i] = max(temp[i], true_ideal[i]) temp[i] = min(temp[i], true_nadir[i]) temp2[i] = max(temp2[i], true_ideal[i]) temp2[i] = min(temp2[i], true_nadir[i]) # TODO (giomara): return the reference point in some other place return np.vstack((temp, temp2)).T ``` ##### generate_reference_point_decision ``` generate_reference_point_decision( ideal_point, translated_front, assigned_vectors, max_assigned_vector, ) -> np.ndarray ``` Generate a reference point for the decision phase. The reference point is based on the solution assigned to the reference vector with the maximum number of assigned solutions and closest to the origin. Parameters: | Name | Type | Description | Default | | --------------------- | --------- | ------------------------------------------------------------------ | ---------- | | `ideal_point` | `ndarray` | The ideal point. | *required* | | `translated_front` | `ndarray` | The translated solution front. | *required* | | `assigned_vectors` | `ndarray` | Indices of assigned reference vectors. | *required* | | `max_assigned_vector` | `int` | Index of the reference vector with the maximum assigned solutions. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------ | | `ndarray` | np.ndarray: The generated reference point. | Source code in `desdeo/adm/adm_afsar.py` ``` def generate_reference_point_decision( self, ideal_point, translated_front, assigned_vectors, max_assigned_vector ) -> np.ndarray: """Generate a reference point for the decision phase. The reference point is based on the solution assigned to the reference vector with the maximum number of assigned solutions and closest to the origin. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. max_assigned_vector (int): Index of the reference vector with the maximum assigned solutions. Returns: np.ndarray: The generated reference point. """ ideal_cf = ideal_point translated_cf = translated_front sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == max_assigned_vector))) sub_population_fitness = translated_cf[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.where(sub_pop_fitness_magnitude == np.nanmin(sub_pop_fitness_magnitude)) distance_selected = sub_pop_fitness_magnitude[minidx] reference_point = distance_selected[0] * self.reference_vectors[max_assigned_vector] return np.squeeze(reference_point + ideal_cf) ``` ##### generate_reference_point_learning ``` generate_reference_point_learning( ideal_point, translated_front, assigned_vectors ) -> np.ndarray ``` Generate a reference point for the learning phase. The reference point is based on the solution assigned to the reference vector with the minimum number of assigned solutions and closest to the origin. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | -------------------------------------- | ---------- | | `ideal_point` | `ndarray` | The ideal point. | *required* | | `translated_front` | `ndarray` | The translated solution front. | *required* | | `assigned_vectors` | `ndarray` | Indices of assigned reference vectors. | *required* | Returns: | Type | Description | | --------- | ---------------------------------------- | | `ndarray` | np.array: The generated reference point. | Source code in `desdeo/adm/adm_afsar.py` ``` def generate_reference_point_learning(self, ideal_point, translated_front, assigned_vectors) -> np.ndarray: """Generate a reference point for the learning phase. The reference point is based on the solution assigned to the reference vector with the minimum number of assigned solutions and closest to the origin. Args: ideal_point (np.ndarray): The ideal point. translated_front (np.ndarray): The translated solution front. assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.array: The generated reference point. """ ideal_cf = ideal_point translated_cf = translated_front number_assigned = np.bincount(assigned_vectors) min_assigned_vector = np.atleast_1d( np.squeeze(np.where(number_assigned == np.min(number_assigned[np.nonzero(number_assigned)]))) ) sub_population_index = np.atleast_1d(np.squeeze(np.where(assigned_vectors == min_assigned_vector[0]))) sub_population_fitness = translated_cf[sub_population_index] sub_pop_fitness_magnitude = np.sqrt(np.sum(np.power(sub_population_fitness, 2), axis=1)) minidx = np.where(sub_pop_fitness_magnitude == np.nanmin(sub_pop_fitness_magnitude)) distance_selected = sub_pop_fitness_magnitude[minidx] reference_point = distance_selected[0] * self.reference_vectors[min_assigned_vector[0]] return np.squeeze(reference_point + ideal_cf) ``` ##### get_max_assigned_vector ``` get_max_assigned_vector(assigned_vectors) -> np.ndarray ``` Find the reference vector with the maximum number of assigned solutions. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | -------------------------------------- | ---------- | | `assigned_vectors` | `ndarray` | Indices of assigned reference vectors. | *required* | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------- | | `ndarray` | np.ndarray: Indices of the reference vector(s) with the maximum assignments. | Source code in `desdeo/adm/adm_afsar.py` ``` def get_max_assigned_vector(self, assigned_vectors) -> np.ndarray: """Find the reference vector with the maximum number of assigned solutions. Args: assigned_vectors (np.ndarray): Indices of assigned reference vectors. Returns: np.ndarray: Indices of the reference vector(s) with the maximum assignments. """ number_assigned = np.bincount(assigned_vectors) return np.atleast_1d( np.squeeze(np.where(number_assigned == np.max(number_assigned[np.nonzero(number_assigned)]))) ) ``` ##### get_next_preference ``` get_next_preference( *fronts: ndarray, preference_type: str = "reference_point", ) -> np.ndarray ``` Generate the next preference based on the current phase and provided solution fronts. Parameters: | Name | Type | Description | Default | | ----------------- | --------- | ------------------------------------------------------ | ------------------- | | `*fronts` | `ndarray` | One or more solution fronts (arrays) to be considered. | `()` | | `preference_type` | `str` | The type of preference to generate. | `'reference_point'` | Returns: | Type | Description | | --------- | ------------------------------------------------- | | `ndarray` | np.ndarray: The generated preference information. | Source code in `desdeo/adm/adm_afsar.py` ``` def get_next_preference(self, *fronts: np.ndarray, preference_type: str = "reference_point") -> np.ndarray: """Generate the next preference based on the current phase and provided solution fronts. Args: *fronts: One or more solution fronts (arrays) to be considered. preference_type (str): The type of preference to generate. Returns: np.ndarray: The generated preference information. """ self.preference_type = preference_type if len(self.composite_front) == 0: self.composite_front = self.generate_composite_front(*fronts) else: self.composite_front = self.generate_composite_front(self.composite_front, *fronts) ideal_point = self.composite_front.min(axis=0) translated_front = self.translate_front(self.composite_front, ideal_point) normalized_front = self.normalize_front(self.composite_front, translated_front) assigned_vectors = self.assign_vectors(normalized_front) if self.iteration_counter < self.it_learning_phase: self.preference = self.generate_preference_learning(ideal_point, translated_front, assigned_vectors) else: if self.iteration_counter == self.it_learning_phase: self.max_assigned_vector = self.get_max_assigned_vector(assigned_vectors) self.preference = self.generate_preference_decision( ideal_point, translated_front, assigned_vectors, self.max_assigned_vector, ) self.iteration_counter += 1 return self.preference ``` ##### normalize_front ``` normalize_front(front, translated_front) -> np.ndarray ``` Normalize the translated front so that each solution has unit length. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | ------------------------------ | ---------- | | `front` | `ndarray` | The original solution front. | *required* | | `translated_front` | `ndarray` | The translated solution front. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------ | | `ndarray` | np.ndarray: The normalized solution front. | Source code in `desdeo/adm/adm_afsar.py` ``` def normalize_front(self, front, translated_front) -> np.ndarray: """Normalize the translated front so that each solution has unit length. Args: front (np.ndarray): The original solution front. translated_front (np.ndarray): The translated solution front. Returns: np.ndarray: The normalized solution front. """ translated_norm = np.linalg.norm(translated_front, axis=1) translated_norm = np.repeat(translated_norm, len(translated_front[0, :])).reshape(len(front), len(front[0, :])) translated_norm[translated_norm == 0] = np.finfo(float).eps return np.divide(translated_front, translated_norm) ``` ##### translate_front ``` translate_front(front, ideal) -> np.ndarray ``` Translate the front by subtracting the ideal point from each solution. Parameters: | Name | Type | Description | Default | | ------- | --------- | ------------------- | ---------- | | `front` | `ndarray` | The solution front. | *required* | | `ideal` | `ndarray` | The ideal point. | *required* | Returns: | Type | Description | | --------- | --------------------------------- | | `ndarray` | np.ndarray: The translated front. | Source code in `desdeo/adm/adm_afsar.py` ``` def translate_front(self, front, ideal) -> np.ndarray: """Translate the front by subtracting the ideal point from each solution. Args: front (np.ndarray): The solution front. ideal (np.ndarray): The ideal point. Returns: np.ndarray: The translated front. """ return np.subtract(front, ideal) ``` ## Templates ### desdeo.emo.methods.templates This module contains the basic functional implementations for the EMO methods. This can be used as a template for the implementation of the EMO methods. #### template1 ``` template1( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: BaseSelector, terminator: BaseTerminator, repair: Callable[[DataFrame], DataFrame] = lambda x: x, ) -> EMOResult ``` Implements a template that many EMO methods, such as RVEA and NSGA-III, follow. Parameters: | Name | Type | Description | Default | | ------------ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | `evaluator` | `EMOEvaluator` | A class that evaluates the solutions and provides the objective vectors, constraint vectors, and targets. | *required* | | `crossover` | `BaseCrossover` | The crossover operator. | *required* | | `mutation` | `BaseMutation` | The mutation operator. | *required* | | `generator` | `BaseGenerator` | A class that generates the initial population. | *required* | | `selection` | `BaseSelector` | The selection operator. | *required* | | `terminator` | `BaseTerminator` | The termination operator. | *required* | | `repair` | `Callable` | A function that repairs the offspring if they go out of bounds. Defaults to an identity function, meaning no repair is done. See desdeo.tools.utils.repair as an example of a repair function. | `lambda x: x` | Returns: | Name | Type | Description | | ----------- | ----------- | --------------------------------------------------------------------------------- | | `EMOResult` | `EMOResult` | The final population and their objective vectors, constraint vectors, and targets | Source code in `desdeo/emo/methods/templates.py` ``` def template1( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: BaseSelector, terminator: BaseTerminator, repair: Callable[[pl.DataFrame], pl.DataFrame] = lambda x: x, # Default to identity function if no repair is needed ) -> EMOResult: """Implements a template that many EMO methods, such as RVEA and NSGA-III, follow. Args: evaluator (EMOEvaluator): A class that evaluates the solutions and provides the objective vectors, constraint vectors, and targets. crossover (BaseCrossover): The crossover operator. mutation (BaseMutation): The mutation operator. generator (BaseGenerator): A class that generates the initial population. selection (BaseSelector): The selection operator. terminator (BaseTerminator): The termination operator. repair (Callable, optional): A function that repairs the offspring if they go out of bounds. Defaults to an identity function, meaning no repair is done. See [desdeo.tools.utils.repair][] as an example of a repair function. Returns: EMOResult: The final population and their objective vectors, constraint vectors, and targets """ solutions, outputs = generator.do() while not terminator.check(): offspring = crossover.do(population=solutions) offspring = mutation.do(offspring, solutions) # Repair offspring if they go out of bounds offspring = repair(offspring) offspring_outputs = evaluator.evaluate(offspring) solutions, outputs = selection.do(parents=(solutions, outputs), offsprings=(offspring, offspring_outputs)) return EMOResult(optimal_variables=solutions, optimal_outputs=outputs) ``` #### template2 ``` template2( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: _FitnessPublishingSelector, mate_selection: BaseScalarSelector, terminator: BaseTerminator, repair: Callable[[DataFrame], DataFrame] = lambda x: x, ) -> EMOResult ``` Implements a template that many EMO methods, such as IBEA, follow. Parameters: | Name | Type | Description | Default | | ---------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | `evaluator` | `EMOEvaluator` | A class that evaluates the solutions and provides the objective vectors, constraint vectors, and targets. | *required* | | `crossover` | `BaseCrossover` | The crossover operator. | *required* | | `mutation` | `BaseMutation` | The mutation operator. | *required* | | `generator` | `BaseGenerator` | A class that generates the initial population. | *required* | | `selection` | `_FitnessPublishingSelector` | The selection operator. It publishes the fitness that mate_selection picks parents by. | *required* | | `mate_selection` | `BaseScalarSelector` | The mating selection operator, which selects parents for mating. This is typically a scalar selector that selects parents based on their fitness. | *required* | | `terminator` | `BaseTerminator` | The termination operator. | *required* | | `repair` | `Callable` | A function that repairs the offspring if they go out of bounds. Defaults to an identity function, meaning no repair is done. See desdeo.tools.utils.repair as an example of a repair function. | `lambda x: x` | Returns: | Name | Type | Description | | ----------- | ----------- | --------------------------------------------------------------------------------- | | `EMOResult` | `EMOResult` | The final population and their objective vectors, constraint vectors, and targets | Source code in `desdeo/emo/methods/templates.py` ``` def template2( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: _FitnessPublishingSelector, mate_selection: BaseScalarSelector, terminator: BaseTerminator, repair: Callable[[pl.DataFrame], pl.DataFrame] = lambda x: x, # Default to identity function if no repair is needed ) -> EMOResult: """Implements a template that many EMO methods, such as IBEA, follow. Args: evaluator (EMOEvaluator): A class that evaluates the solutions and provides the objective vectors, constraint vectors, and targets. crossover (BaseCrossover): The crossover operator. mutation (BaseMutation): The mutation operator. generator (BaseGenerator): A class that generates the initial population. selection (_FitnessPublishingSelector): The selection operator. It publishes the fitness that `mate_selection` picks parents by. mate_selection (BaseScalarSelector): The mating selection operator, which selects parents for mating. This is typically a scalar selector that selects parents based on their fitness. terminator (BaseTerminator): The termination operator. repair (Callable, optional): A function that repairs the offspring if they go out of bounds. Defaults to an identity function, meaning no repair is done. See [desdeo.tools.utils.repair][] as an example of a repair function. Returns: EMOResult: The final population and their objective vectors, constraint vectors, and targets """ if not isinstance(selection, _FitnessPublishingSelector): raise TypeError( "The selection operator must be a subclass of _FitnessPublishingSelector, which publishes the fitness " "that mate_selection picks parents by." ) solutions, outputs = generator.do() # This is just a hack to make all selection operators work (they require offsprings to be passed separately rn) offspring = pl.DataFrame( schema=solutions.schema, ) offspring_outputs = pl.DataFrame( schema=outputs.schema, ) while True: solutions, outputs = selection.do(parents=(solutions, outputs), offsprings=(offspring, offspring_outputs)) if terminator.check(): # Weird way to do looping, but IBEA does environmental selection before the loop check, and... # does mating afterwards. break parents, _ = mate_selection.do((solutions, outputs)) offspring = crossover.do(population=parents) offspring = mutation.do(offspring, solutions) # Repair offspring if they go out of bounds offspring = repair(offspring) offspring_outputs = evaluator.evaluate(offspring) return EMOResult(optimal_variables=solutions, optimal_outputs=outputs) ``` #### template3 ``` template3( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: BaseSelector, terminator: BaseTerminator, seed: int, repair: Callable[[DataFrame], DataFrame] = lambda x: x, ) -> EMOResult ``` Implements a template that many steady state EMO methods such as SMS-EMOA follow. The algorithm follows the one described in Beume et al. (2007). Beume, N., Naujoks, B., & Emmerich, M. (2007). SMS-EMOA: Multiobjective selection based on dominated hypervolume. European Journal of Operational Research, 181(3), 1653-1669. https://doi.org/10.1016/j.ejor.2006.08.008 Parameters: | Name | Type | Description | Default | | ------------ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | `evaluator` | `EMOEvaluator` | A class that evaluates the solutions and provides the objective vectors, constraint vectors, and targets. | *required* | | `crossover` | `BaseCrossover` | The crossover operator. | *required* | | `mutation` | `BaseMutation` | The mutation operator. | *required* | | `generator` | `BaseGenerator` | A class that generates the initial population. | *required* | | `selection` | `BaseSelector` | The selection operator. | *required* | | `terminator` | `BaseTerminator` | The termination operator. | *required* | | `seed` | `int` | The random seed for reproducibility. | *required* | | `repair` | `Callable` | A function that repairs the offspring if they go out of bounds. Defaults to an identity function, meaning no repair is done. See desdeo.tools.utils.repair as an example of a repair function. | `lambda x: x` | Returns: | Name | Type | Description | | ----------- | ----------- | --------------------------------------------------------------------------------- | | `EMOResult` | `EMOResult` | The final population and their objective vectors, constraint vectors, and targets | Source code in `desdeo/emo/methods/templates.py` ``` def template3( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: BaseSelector, terminator: BaseTerminator, seed: int, repair: Callable[[pl.DataFrame], pl.DataFrame] = lambda x: x, # Default to identity function if no repair is needed ) -> EMOResult: """Implements a template that many steady state EMO methods such as SMS-EMOA follow. The algorithm follows the one described in Beume et al. (2007). Beume, N., Naujoks, B., & Emmerich, M. (2007). SMS-EMOA: Multiobjective selection based on dominated hypervolume. European Journal of Operational Research, 181(3), 1653-1669. https://doi.org/10.1016/j.ejor.2006.08.008 Args: evaluator (EMOEvaluator): A class that evaluates the solutions and provides the objective vectors, constraint vectors, and targets. crossover (BaseCrossover): The crossover operator. mutation (BaseMutation): The mutation operator. generator (BaseGenerator): A class that generates the initial population. selection (BaseSelector): The selection operator. terminator (BaseTerminator): The termination operator. seed (int): The random seed for reproducibility. repair (Callable, optional): A function that repairs the offspring if they go out of bounds. Defaults to an identity function, meaning no repair is done. See [desdeo.tools.utils.repair][] as an example of a repair function. Returns: EMOResult: The final population and their objective vectors, constraint vectors, and targets """ rng = np.random.default_rng(seed) solutions, outputs = generator.do() # Algorithm 1 line 1 while not terminator.check(): # Generate one offspring at a time # choose two random parents from the current population parents_idx = rng.choice(solutions.height, size=2, replace=False).tolist() offsprings = crossover.do(population=solutions, to_mate=parents_idx) # Algorithm 1 line 4 offsprings = mutation.do(offsprings, solutions) # Algorithm 1 line 4 # Repair offspring if they go out of bounds offsprings = repair(offsprings) # The crossover generates two offsprings, but we only want to keep one of them, # so we randomly choose one of the two (i think just always choosing the first one is not fine) offspring_idx = rng.choice(offsprings.height, size=1, replace=False).tolist() offspring = offsprings[offspring_idx, :] offspring_outputs = evaluator.evaluate(offspring) solutions, outputs = selection.do( parents=(solutions, outputs), offsprings=(offspring, offspring_outputs) ) # Algorithm 1 line 5 return EMOResult(optimal_variables=solutions, optimal_outputs=outputs) ``` #### template_moead ``` template_moead( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: MOEADSelector, terminator: BaseTerminator, seed: int, repair: Callable[[DataFrame], DataFrame] = lambda x: x, ) -> EMOResult ``` Implements the main loop of MOEA/D and MOEA/D-DE. Each generation visits the subproblems in order. For subproblem `i` it draws a mating pool, makes one offspring from parents in that pool, evaluates it, and lets it replace solutions in the pool straight away, so the next subproblem already mates with the updated population. A generation therefore spends exactly as many evaluations as there are subproblems, one at a time. How the parents are drawn depends on the crossover. For DifferentialEvolutionCrossover the current solution `x_i` is the target and the donors come from the pool (MOEA/D-DE, Step 2.2); set its `base_vector` to "target" to get MOEA/D-DE's `x_i + F * (x_r2 - x_r3)`. Any other crossover gets two distinct parents drawn from the pool (MOEA/D, Step 2.1), and one of the children it returns is kept at random. The final population, one solution per subproblem, is returned. Neither paper's continuous experiments keep the external population of nondominated solutions (Zhang and Li 2007, Section V-C); use the template's archive for that. References Zhang, Q., & Li, H. (2007). MOEA/D: A multiobjective evolutionary algorithm based on decomposition. IEEE Transactions on Evolutionary Computation, 11(6), 712-731. https://doi.org/10.1109/TEVC.2007.892759 Li, H., & Zhang, Q. (2009). Multiobjective optimization problems with complicated Pareto sets, MOEA/D and NSGA-II. IEEE Transactions on Evolutionary Computation, 13(2), 284-302. https://doi.org/10.1109/TEVC.2008.925798 Parameters: | Name | Type | Description | Default | | ------------ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | `evaluator` | `EMOEvaluator` | A class that evaluates the solutions and provides the objective vectors, constraint vectors, and targets. | *required* | | `crossover` | `BaseCrossover` | The crossover operator. | *required* | | `mutation` | `BaseMutation` | The mutation operator. | *required* | | `generator` | `BaseGenerator` | A class that generates the initial population, one solution per subproblem. | *required* | | `selection` | `MOEADSelector` | The MOEA/D selector, which holds the weight vectors, the neighbourhoods and the ideal point. | *required* | | `terminator` | `BaseTerminator` | The termination operator, checked once per generation. | *required* | | `seed` | `int` | The random seed for drawing parents from the mating pool. | *required* | | `repair` | `Callable` | A function that repairs the offspring if they go out of bounds. Defaults to an identity function, meaning no repair is done. See desdeo.tools.utils.repair as an example of a repair function. | `lambda x: x` | Returns: | Name | Type | Description | | ----------- | ----------- | --------------------------------------------------------------------------------- | | `EMOResult` | `EMOResult` | The final population and their objective vectors, constraint vectors, and targets | Source code in `desdeo/emo/methods/templates.py` ``` def template_moead( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: MOEADSelector, terminator: BaseTerminator, seed: int, repair: Callable[[pl.DataFrame], pl.DataFrame] = lambda x: x, # Default to identity function if no repair is needed ) -> EMOResult: """Implements the main loop of MOEA/D and MOEA/D-DE. Each generation visits the subproblems in order. For subproblem `i` it draws a mating pool, makes one offspring from parents in that pool, evaluates it, and lets it replace solutions in the pool straight away, so the next subproblem already mates with the updated population. A generation therefore spends exactly as many evaluations as there are subproblems, one at a time. How the parents are drawn depends on the crossover. For [DifferentialEvolutionCrossover][desdeo.emo.operators.crossover.DifferentialEvolutionCrossover] the current solution `x_i` is the target and the donors come from the pool (MOEA/D-DE, Step 2.2); set its `base_vector` to "target" to get MOEA/D-DE's `x_i + F * (x_r2 - x_r3)`. Any other crossover gets two distinct parents drawn from the pool (MOEA/D, Step 2.1), and one of the children it returns is kept at random. The final population, one solution per subproblem, is returned. Neither paper's continuous experiments keep the external population of nondominated solutions (Zhang and Li 2007, Section V-C); use the template's archive for that. References: Zhang, Q., & Li, H. (2007). MOEA/D: A multiobjective evolutionary algorithm based on decomposition. IEEE Transactions on Evolutionary Computation, 11(6), 712-731. https://doi.org/10.1109/TEVC.2007.892759 Li, H., & Zhang, Q. (2009). Multiobjective optimization problems with complicated Pareto sets, MOEA/D and NSGA-II. IEEE Transactions on Evolutionary Computation, 13(2), 284-302. https://doi.org/10.1109/TEVC.2008.925798 Args: evaluator (EMOEvaluator): A class that evaluates the solutions and provides the objective vectors, constraint vectors, and targets. crossover (BaseCrossover): The crossover operator. mutation (BaseMutation): The mutation operator. generator (BaseGenerator): A class that generates the initial population, one solution per subproblem. selection (MOEADSelector): The MOEA/D selector, which holds the weight vectors, the neighbourhoods and the ideal point. terminator (BaseTerminator): The termination operator, checked once per generation. seed (int): The random seed for drawing parents from the mating pool. repair (Callable, optional): A function that repairs the offspring if they go out of bounds. Defaults to an identity function, meaning no repair is done. See [desdeo.tools.utils.repair][] as an example of a repair function. Returns: EMOResult: The final population and their objective vectors, constraint vectors, and targets """ rng = np.random.default_rng(seed) target_aligned = isinstance(crossover, DifferentialEvolutionCrossover) solutions, outputs = generator.do() # 2007 Step 1.3, 2009 Step 1.2 # The neighbourhoods (2007 Step 1.2, 2009 Step 1.1) were built with the selector; this sets z. solutions, outputs = selection.do(parents=(solutions, outputs), offsprings=(solutions.clear(), outputs.clear())) while not terminator.check(): for i in range(selection.number_of_subproblems): # Step 2 pool = selection.mating_pool(i) # 2009 Step 2.1 if target_aligned: # 2009 Step 2.2: r1 = i, and r2, r3 from the pool. position = int(np.flatnonzero(pool == i)[0]) offspring = crossover.do(population=solutions[pool.tolist()], to_mate=[position]) else: # 2007 Step 2.1: two parents from B(i), and one offspring. parents = rng.choice(pool, size=2, replace=False).tolist() offspring = crossover.do(population=solutions, to_mate=parents) offspring = offspring[[int(rng.integers(offspring.height))]] offspring = mutation.do(offspring, solutions) offspring = repair(offspring) # 2009 Step 2.3 offspring_outputs = evaluator.evaluate(offspring) # 2007 Steps 2.3-2.4, 2009 Steps 2.4-2.5 solutions, outputs = selection.do(parents=(solutions, outputs), offsprings=(offspring, offspring_outputs)) selection.notify() return EMOResult(optimal_variables=solutions, optimal_outputs=outputs) ``` #### template_xlemoo ``` template_xlemoo( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: BaseScalarSelector, learning_operator: LearningModeOperator, terminator: BaseTerminator, repair: Callable[[DataFrame], DataFrame] = lambda x: x, n_darwin_per_cycle: int = 20, n_learning_per_cycle: int = 1, ) -> EMOResult ``` Implements the XLEMOO loop alternating between Darwinian and Learning modes. The loop interleaves `n_darwin_per_cycle` Darwinian iterations with `n_learning_per_cycle` Learning iterations. Each iteration counts as one generation against the terminator, so the cycle structure is just a phase selector for what happens inside that generation. Parameters: | Name | Type | Description | Default | | ---------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | | `evaluator` | `EMOEvaluator` | Evaluator for objective and target values. | *required* | | `crossover` | `BaseCrossover` | The crossover operator. | *required* | | `mutation` | `BaseMutation` | The mutation operator. | *required* | | `generator` | `BaseGenerator` | Initial population generator. | *required* | | `selection` | `BaseScalarSelector` | Scalar selector that ranks the combined parent and offspring population by a single fitness column (e.g. ElitistSelection). | *required* | | `learning_operator` | `LearningModeOperator` | Operator that performs one learning step (rule extraction + instantiation) using the archive. Its do() returns instantiated decision vectors (or None when no rules can be extracted). | *required* | | `terminator` | `BaseTerminator` | Termination operator. Its check() advances the generation counter and notifies subscribers (e.g. the Archive). | *required* | | `repair` | `Callable` | Function repairing offspring back into bounds. Defaults to identity. | `lambda x: x` | | `n_darwin_per_cycle` | `int` | Number of Darwinian iterations per cycle. Defaults to 20. | `20` | | `n_learning_per_cycle` | `int` | Number of Learning iterations per cycle. Set to 0 to disable Learning mode entirely. Defaults to 1. | `1` | Returns: | Name | Type | Description | | ----------- | ----------- | ----------------------------------------------------- | | `EMOResult` | `EMOResult` | The final population and its objective/target values. | Source code in `desdeo/emo/methods/templates.py` ``` def template_xlemoo( evaluator: EMOEvaluator, crossover: BaseCrossover, mutation: BaseMutation, generator: BaseGenerator, selection: BaseScalarSelector, learning_operator: LearningModeOperator, terminator: BaseTerminator, repair: Callable[[pl.DataFrame], pl.DataFrame] = lambda x: x, n_darwin_per_cycle: int = 20, n_learning_per_cycle: int = 1, ) -> EMOResult: """Implements the XLEMOO loop alternating between Darwinian and Learning modes. The loop interleaves ``n_darwin_per_cycle`` Darwinian iterations with ``n_learning_per_cycle`` Learning iterations. Each iteration counts as one generation against the terminator, so the cycle structure is just a phase selector for what happens inside that generation. Args: evaluator (EMOEvaluator): Evaluator for objective and target values. crossover (BaseCrossover): The crossover operator. mutation (BaseMutation): The mutation operator. generator (BaseGenerator): Initial population generator. selection (BaseScalarSelector): Scalar selector that ranks the combined parent and offspring population by a single fitness column (e.g. [ElitistSelection][desdeo.emo.operators.scalar_selection.ElitistSelection]). learning_operator (LearningModeOperator): Operator that performs one learning step (rule extraction + instantiation) using the archive. Its `do()` returns instantiated decision vectors (or ``None`` when no rules can be extracted). terminator (BaseTerminator): Termination operator. Its ``check()`` advances the generation counter and notifies subscribers (e.g. the Archive). repair (Callable, optional): Function repairing offspring back into bounds. Defaults to identity. n_darwin_per_cycle (int, optional): Number of Darwinian iterations per cycle. Defaults to 20. n_learning_per_cycle (int, optional): Number of Learning iterations per cycle. Set to 0 to disable Learning mode entirely. Defaults to 1. Returns: EMOResult: The final population and its objective/target values. """ if n_darwin_per_cycle == 0 and n_learning_per_cycle == 0: raise ValueError("At least one of n_darwin_per_cycle and n_learning_per_cycle must be > 0.") cycle_len = n_darwin_per_cycle + n_learning_per_cycle solutions, outputs = generator.do() gen_in_cycle = 0 while not terminator.check(): if gen_in_cycle < n_darwin_per_cycle: offspring = crossover.do(population=solutions) offspring = mutation.do(offspring, solutions) offspring = repair(offspring) offspring_outputs = evaluator.evaluate(offspring) combined_decvars = solutions.vstack(offspring) combined_outputs = outputs.vstack(offspring_outputs) solutions, outputs = selection.do((combined_decvars, combined_outputs)) else: instantiated = learning_operator.do() if instantiated is not None: instantiated_outputs = evaluator.evaluate(instantiated) combined_decvars = solutions.vstack(instantiated) combined_outputs = outputs.vstack(instantiated_outputs) solutions, outputs = selection.do((combined_decvars, combined_outputs)) # else: no usable rules this round; keep the current population unchanged gen_in_cycle = (gen_in_cycle + 1) % cycle_len return EMOResult(optimal_variables=solutions, optimal_outputs=outputs) ``` ## Generators ### desdeo.emo.operators.generator Class for generating initial population for the evolutionary optimization algorithms. #### ArchiveGenerator Bases: `BaseGenerator` Class for getting initial population from an archive. Source code in `desdeo/emo/operators/generator.py` ``` class ArchiveGenerator(BaseGenerator): """Class for getting initial population from an archive.""" def __init__( self, problem: Problem, evaluator: EMOEvaluator, publisher: Publisher, verbosity: int, solutions: pl.DataFrame, **kwargs: dict, # just to dump seed ): """Initialize the ArchiveGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. Only used to check that the outputs have the correct variables. publisher (Publisher): The publisher to publish the messages. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. solutions (pl.DataFrame): The decision variable vectors to use as the initial population. kwargs (dict): Other keyword arguments to pass, e.g., a random seed. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if not isinstance(solutions, pl.DataFrame): raise TypeError("The solutions must be a polars DataFrame.") if solutions.shape[0] == 0: raise ValueError("The solutions DataFrame is empty.") self.solutions = solutions # self.outputs = outputs if not set(self.solutions.columns) == set(self.variable_symbols): raise ValueError("The solutions DataFrame must have the same columns as the problem variables.") # TODO: Check that the outputs have the correct columns self.evaluator = evaluator def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Get the initial population from the archive. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ self.outputs = self.evaluator.evaluate(self.solutions) self.notify() return self.solutions, self.outputs def state(self) -> Sequence[Message]: """Return the state of the generator. This method overrides the state method of the BaseGenerator class, because the solutions and outputs are already provided and not generated by the generator. Returns: dict: The state of the generator. """ # TODO: Should we do it like this? Or just do super().state()? # Maybe saying that zero evaluations have been done is misleading? # idk if self.verbosity == 0: return [] if self.verbosity == 1: return [ IntMessage( topic=GeneratorMessageTopics.NEW_EVALUATIONS, value=0, source=self.__class__.__name__, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=GeneratorMessageTopics.VERBOSE_OUTPUTS, value=self.solutions.hstack(self.outputs), source=self.__class__.__name__, ), IntMessage( topic=GeneratorMessageTopics.NEW_EVALUATIONS, value=0, source=self.__class__.__name__, ), ] def update(self, message) -> None: """Update the generator based on the message.""" ``` ##### __init__ ``` __init__( problem: Problem, evaluator: EMOEvaluator, publisher: Publisher, verbosity: int, solutions: DataFrame, **kwargs: dict, ) ``` Initialize the ArchiveGenerator class. Parameters: | Name | Type | Description | Default | | ----------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem to solve. | *required* | | `evaluator` | `BaseEvaluator` | The evaluator to evaluate the population. Only used to check that the outputs have the correct variables. | *required* | | `publisher` | `Publisher` | The publisher to publish the messages. | *required* | | `verbosity` | `int` | The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. | *required* | | `solutions` | `DataFrame` | The decision variable vectors to use as the initial population. | *required* | | `kwargs` | `dict` | Other keyword arguments to pass, e.g., a random seed. | `{}` | Source code in `desdeo/emo/operators/generator.py` ``` def __init__( self, problem: Problem, evaluator: EMOEvaluator, publisher: Publisher, verbosity: int, solutions: pl.DataFrame, **kwargs: dict, # just to dump seed ): """Initialize the ArchiveGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. Only used to check that the outputs have the correct variables. publisher (Publisher): The publisher to publish the messages. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. solutions (pl.DataFrame): The decision variable vectors to use as the initial population. kwargs (dict): Other keyword arguments to pass, e.g., a random seed. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if not isinstance(solutions, pl.DataFrame): raise TypeError("The solutions must be a polars DataFrame.") if solutions.shape[0] == 0: raise ValueError("The solutions DataFrame is empty.") self.solutions = solutions # self.outputs = outputs if not set(self.solutions.columns) == set(self.variable_symbols): raise ValueError("The solutions DataFrame must have the same columns as the problem variables.") # TODO: Check that the outputs have the correct columns self.evaluator = evaluator ``` ##### do ``` do() -> tuple[pl.DataFrame, pl.DataFrame] ``` Get the initial population from the archive. Returns: | Type | Description | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[DataFrame, DataFrame]` | tuple\[pl.DataFrame, pl.DataFrame\]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. | Source code in `desdeo/emo/operators/generator.py` ``` def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Get the initial population from the archive. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ self.outputs = self.evaluator.evaluate(self.solutions) self.notify() return self.solutions, self.outputs ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the generator. This method overrides the state method of the BaseGenerator class, because the solutions and outputs are already provided and not generated by the generator. Returns: | Name | Type | Description | | ------ | ------------------- | --------------------------- | | `dict` | `Sequence[Message]` | The state of the generator. | Source code in `desdeo/emo/operators/generator.py` ``` def state(self) -> Sequence[Message]: """Return the state of the generator. This method overrides the state method of the BaseGenerator class, because the solutions and outputs are already provided and not generated by the generator. Returns: dict: The state of the generator. """ # TODO: Should we do it like this? Or just do super().state()? # Maybe saying that zero evaluations have been done is misleading? # idk if self.verbosity == 0: return [] if self.verbosity == 1: return [ IntMessage( topic=GeneratorMessageTopics.NEW_EVALUATIONS, value=0, source=self.__class__.__name__, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=GeneratorMessageTopics.VERBOSE_OUTPUTS, value=self.solutions.hstack(self.outputs), source=self.__class__.__name__, ), IntMessage( topic=GeneratorMessageTopics.NEW_EVALUATIONS, value=0, source=self.__class__.__name__, ), ] ``` ##### update ``` update(message) -> None ``` Update the generator based on the message. Source code in `desdeo/emo/operators/generator.py` ``` def update(self, message) -> None: """Update the generator based on the message.""" ``` #### BaseGenerator Bases: `Subscriber` Base class for generating initial population for the evolutionary optimization algorithms. This class should be inherited by the classes that implement the initial population generation for the evolutionary optimization algorithms. Source code in `desdeo/emo/operators/generator.py` ``` class BaseGenerator(Subscriber): """Base class for generating initial population for the evolutionary optimization algorithms. This class should be inherited by the classes that implement the initial population generation for the evolutionary optimization algorithms. """ @property def provided_topics(self) -> dict[int, Sequence[GeneratorMessageTopics]]: """Return the topics provided by the generator. Returns: dict[int, Sequence[GeneratorMessageTopics]]: The topics provided by the generator. """ return { 0: [], 1: [GeneratorMessageTopics.NEW_EVALUATIONS], 2: [ GeneratorMessageTopics.NEW_EVALUATIONS, GeneratorMessageTopics.VERBOSE_OUTPUTS, ], } @property def interested_topics(self): """Return the message topics that the generator is interested in.""" return [] def __init__(self, problem: Problem, publisher: Publisher, verbosity: int): """Initialize the BaseGenerator class.""" super().__init__(publisher=publisher, verbosity=verbosity) self.problem = problem self.variable_symbols = [var.symbol for var in problem.get_flattened_variables()] self.bounds = np.array([[var.lowerbound, var.upperbound] for var in problem.get_flattened_variables()]) self.population: pl.DataFrame = None self.out: pl.DataFrame = None @abstractmethod def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. This method should be implemented by the inherited classes. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ def state(self) -> Sequence[Message]: """Return the state of the generator. This method should be implemented by the inherited classes. Returns: dict: The state of the generator. """ if self.population is None or self.out is None or self.verbosity == 0: return [] if self.verbosity == 1: return [ IntMessage( topic=GeneratorMessageTopics.NEW_EVALUATIONS, value=self.population.shape[0], source=self.__class__.__name__, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=GeneratorMessageTopics.VERBOSE_OUTPUTS, value=self.population.hstack(self.out), source=self.__class__.__name__, ), IntMessage( topic=GeneratorMessageTopics.NEW_EVALUATIONS, value=self.population.shape[0], source=self.__class__.__name__, ), ] ``` ##### interested_topics ``` interested_topics ``` Return the message topics that the generator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[GeneratorMessageTopics]] ``` Return the topics provided by the generator. Returns: | Type | Description | | --------------------------------------------- | ------------------------------------------------------------------------------------ | | `dict[int, Sequence[GeneratorMessageTopics]]` | dict\[int, Sequence[GeneratorMessageTopics]\]: The topics provided by the generator. | ##### __init__ ``` __init__( problem: Problem, publisher: Publisher, verbosity: int ) ``` Initialize the BaseGenerator class. Source code in `desdeo/emo/operators/generator.py` ``` def __init__(self, problem: Problem, publisher: Publisher, verbosity: int): """Initialize the BaseGenerator class.""" super().__init__(publisher=publisher, verbosity=verbosity) self.problem = problem self.variable_symbols = [var.symbol for var in problem.get_flattened_variables()] self.bounds = np.array([[var.lowerbound, var.upperbound] for var in problem.get_flattened_variables()]) self.population: pl.DataFrame = None self.out: pl.DataFrame = None ``` ##### do ``` do() -> tuple[pl.DataFrame, pl.DataFrame] ``` Generate the initial population. This method should be implemented by the inherited classes. Returns: | Type | Description | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[DataFrame, DataFrame]` | tuple\[pl.DataFrame, pl.DataFrame\]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. | Source code in `desdeo/emo/operators/generator.py` ``` @abstractmethod def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. This method should be implemented by the inherited classes. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the generator. This method should be implemented by the inherited classes. Returns: | Name | Type | Description | | ------ | ------------------- | --------------------------- | | `dict` | `Sequence[Message]` | The state of the generator. | Source code in `desdeo/emo/operators/generator.py` ``` def state(self) -> Sequence[Message]: """Return the state of the generator. This method should be implemented by the inherited classes. Returns: dict: The state of the generator. """ if self.population is None or self.out is None or self.verbosity == 0: return [] if self.verbosity == 1: return [ IntMessage( topic=GeneratorMessageTopics.NEW_EVALUATIONS, value=self.population.shape[0], source=self.__class__.__name__, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=GeneratorMessageTopics.VERBOSE_OUTPUTS, value=self.population.hstack(self.out), source=self.__class__.__name__, ), IntMessage( topic=GeneratorMessageTopics.NEW_EVALUATIONS, value=self.population.shape[0], source=self.__class__.__name__, ), ] ``` #### LHSGenerator Bases: `BaseGenerator` Class for generating Latin Hypercube Sampling (LHS) initial population for the MOEAs. This class generates the initial population by using the Latin Hypercube Sampling (LHS) method. If the seed is not provided, the seed is set to 0. Source code in `desdeo/emo/operators/generator.py` ``` class LHSGenerator(BaseGenerator): """Class for generating Latin Hypercube Sampling (LHS) initial population for the MOEAs. This class generates the initial population by using the Latin Hypercube Sampling (LHS) method. If the seed is not provided, the seed is set to 0. """ def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the LHSGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.n_points = n_points self.evaluator = evaluator self.seed = seed rng = np.random.default_rng(self.seed) self.lhsrng = LatinHypercube(d=len(self.variable_symbols), rng=rng) def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. This method should be implemented by the inherited classes. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out self.population = pl.from_numpy( self.lhsrng.random(n=self.n_points) * (self.bounds[:, 1] - self.bounds[:, 0]) + self.bounds[:, 0], schema=self.variable_symbols, ) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out def update(self, message) -> None: """Update the generator based on the message.""" ``` ##### __init__ ``` __init__( problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher, ) ``` Initialize the LHSGenerator class. Parameters: | Name | Type | Description | Default | | ----------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem to solve. | *required* | | `evaluator` | `BaseEvaluator` | The evaluator to evaluate the population. | *required* | | `n_points` | `int` | The number of points to generate for the initial population. | *required* | | `seed` | `int` | The seed for the random number generator. | *required* | | `verbosity` | `int` | The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. | *required* | | `publisher` | `Publisher` | The publisher to publish the messages. | *required* | Source code in `desdeo/emo/operators/generator.py` ``` def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the LHSGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.n_points = n_points self.evaluator = evaluator self.seed = seed rng = np.random.default_rng(self.seed) self.lhsrng = LatinHypercube(d=len(self.variable_symbols), rng=rng) ``` ##### do ``` do() -> tuple[pl.DataFrame, pl.DataFrame] ``` Generate the initial population. This method should be implemented by the inherited classes. Returns: | Type | Description | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[DataFrame, DataFrame]` | tuple\[pl.DataFrame, pl.DataFrame\]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. | Source code in `desdeo/emo/operators/generator.py` ``` def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. This method should be implemented by the inherited classes. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out self.population = pl.from_numpy( self.lhsrng.random(n=self.n_points) * (self.bounds[:, 1] - self.bounds[:, 0]) + self.bounds[:, 0], schema=self.variable_symbols, ) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out ``` ##### update ``` update(message) -> None ``` Update the generator based on the message. Source code in `desdeo/emo/operators/generator.py` ``` def update(self, message) -> None: """Update the generator based on the message.""" ``` #### RandomBinaryGenerator Bases: `BaseGenerator` Class for generating random initial population for problems with binary variables. This class generates an initial population by randomly setting variable values to be either 0 or 1. Source code in `desdeo/emo/operators/generator.py` ``` class RandomBinaryGenerator(BaseGenerator): """Class for generating random initial population for problems with binary variables. This class generates an initial population by randomly setting variable values to be either 0 or 1. """ def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the RandomBinaryGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.n_points = n_points self.evaluator = evaluator self.rng = np.random.default_rng(seed) self.seed = seed def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out self.population = pl.from_numpy( self.rng.integers(low=0, high=2, size=(self.n_points, self.bounds.shape[0])).astype(dtype=np.float64), schema=self.variable_symbols, ) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out def update(self, message) -> None: """Update the generator based on the message.""" ``` ##### __init__ ``` __init__( problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher, ) ``` Initialize the RandomBinaryGenerator class. Parameters: | Name | Type | Description | Default | | ----------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem to solve. | *required* | | `evaluator` | `BaseEvaluator` | The evaluator to evaluate the population. | *required* | | `n_points` | `int` | The number of points to generate for the initial population. | *required* | | `seed` | `int` | The seed for the random number generator. | *required* | | `verbosity` | `int` | The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. | *required* | | `publisher` | `Publisher` | The publisher to publish the messages. | *required* | Source code in `desdeo/emo/operators/generator.py` ``` def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the RandomBinaryGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.n_points = n_points self.evaluator = evaluator self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do() -> tuple[pl.DataFrame, pl.DataFrame] ``` Generate the initial population. Returns: | Type | Description | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[DataFrame, DataFrame]` | tuple\[pl.DataFrame, pl.DataFrame\]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. | Source code in `desdeo/emo/operators/generator.py` ``` def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out self.population = pl.from_numpy( self.rng.integers(low=0, high=2, size=(self.n_points, self.bounds.shape[0])).astype(dtype=np.float64), schema=self.variable_symbols, ) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out ``` ##### update ``` update(message) -> None ``` Update the generator based on the message. Source code in `desdeo/emo/operators/generator.py` ``` def update(self, message) -> None: """Update the generator based on the message.""" ``` #### RandomGenerator Bases: `BaseGenerator` Class for generating random initial population for the evolutionary optimization algorithms. This class generates the initial population by randomly sampling the points from the variable bounds. The distribution of the points is uniform. If the seed is not provided, the seed is set to 0. Source code in `desdeo/emo/operators/generator.py` ``` class RandomGenerator(BaseGenerator): """Class for generating random initial population for the evolutionary optimization algorithms. This class generates the initial population by randomly sampling the points from the variable bounds. The distribution of the points is uniform. If the seed is not provided, the seed is set to 0. """ def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the RandomGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.n_points = n_points self.evaluator = evaluator self.rng = np.random.default_rng(seed) self.seed = seed def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. This method should be implemented by the inherited classes. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out self.population = pl.from_numpy( self.rng.uniform(low=self.bounds[:, 0], high=self.bounds[:, 1], size=(self.n_points, self.bounds.shape[0])), schema=self.variable_symbols, ) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out def update(self, message) -> None: """Update the generator based on the message.""" ``` ##### __init__ ``` __init__( problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher, ) ``` Initialize the RandomGenerator class. Parameters: | Name | Type | Description | Default | | ----------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem to solve. | *required* | | `evaluator` | `BaseEvaluator` | The evaluator to evaluate the population. | *required* | | `n_points` | `int` | The number of points to generate for the initial population. | *required* | | `seed` | `int` | The seed for the random number generator. | *required* | | `verbosity` | `int` | The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. | *required* | | `publisher` | `Publisher` | The publisher to publish the messages. | *required* | Source code in `desdeo/emo/operators/generator.py` ``` def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the RandomGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.n_points = n_points self.evaluator = evaluator self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do() -> tuple[pl.DataFrame, pl.DataFrame] ``` Generate the initial population. This method should be implemented by the inherited classes. Returns: | Type | Description | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[DataFrame, DataFrame]` | tuple\[pl.DataFrame, pl.DataFrame\]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. | Source code in `desdeo/emo/operators/generator.py` ``` def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. This method should be implemented by the inherited classes. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out self.population = pl.from_numpy( self.rng.uniform(low=self.bounds[:, 0], high=self.bounds[:, 1], size=(self.n_points, self.bounds.shape[0])), schema=self.variable_symbols, ) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out ``` ##### update ``` update(message) -> None ``` Update the generator based on the message. Source code in `desdeo/emo/operators/generator.py` ``` def update(self, message) -> None: """Update the generator based on the message.""" ``` #### RandomIntegerGenerator Bases: `BaseGenerator` Class for generating random initial population for problems with integer variables. This class generates an initial population by randomly setting variable values to be integers between the bounds of the variables. Source code in `desdeo/emo/operators/generator.py` ``` class RandomIntegerGenerator(BaseGenerator): """Class for generating random initial population for problems with integer variables. This class generates an initial population by randomly setting variable values to be integers between the bounds of the variables. """ def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the RandomIntegerGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.n_points = n_points self.evaluator = evaluator self.rng = np.random.default_rng(seed) self.seed = seed def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out self.population = pl.from_numpy( self.rng.integers( low=self.bounds[:, 0], high=self.bounds[:, 1], size=(self.n_points, self.bounds.shape[0]), endpoint=True, ).astype(dtype=float), schema=self.variable_symbols, ) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out def update(self, message) -> None: """Update the generator based on the message.""" ``` ##### __init__ ``` __init__( problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher, ) ``` Initialize the RandomIntegerGenerator class. Parameters: | Name | Type | Description | Default | | ----------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem to solve. | *required* | | `evaluator` | `BaseEvaluator` | The evaluator to evaluate the population. | *required* | | `n_points` | `int` | The number of points to generate for the initial population. | *required* | | `seed` | `int` | The seed for the random number generator. | *required* | | `verbosity` | `int` | The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. | *required* | | `publisher` | `Publisher` | The publisher to publish the messages. | *required* | Source code in `desdeo/emo/operators/generator.py` ``` def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the RandomIntegerGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.n_points = n_points self.evaluator = evaluator self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do() -> tuple[pl.DataFrame, pl.DataFrame] ``` Generate the initial population. Returns: | Type | Description | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[DataFrame, DataFrame]` | tuple\[pl.DataFrame, pl.DataFrame\]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. | Source code in `desdeo/emo/operators/generator.py` ``` def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out self.population = pl.from_numpy( self.rng.integers( low=self.bounds[:, 0], high=self.bounds[:, 1], size=(self.n_points, self.bounds.shape[0]), endpoint=True, ).astype(dtype=float), schema=self.variable_symbols, ) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out ``` ##### update ``` update(message) -> None ``` Update the generator based on the message. Source code in `desdeo/emo/operators/generator.py` ``` def update(self, message) -> None: """Update the generator based on the message.""" ``` #### RandomMixedIntegerGenerator Bases: `BaseGenerator` Class for generating random initial population for problems with mixed-integer variables. This class generates an initial population by randomly setting variable values to be integers or floats between the bounds of the variables. Source code in `desdeo/emo/operators/generator.py` ``` class RandomMixedIntegerGenerator(BaseGenerator): """Class for generating random initial population for problems with mixed-integer variables. This class generates an initial population by randomly setting variable values to be integers or floats between the bounds of the variables. """ def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the RandomMixedIntegerGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.var_symbol_types = { VariableTypeEnum.real: [ var.symbol for var in problem.variables if var.variable_type == VariableTypeEnum.real ], VariableTypeEnum.integer: [ var.symbol for var in problem.variables if var.variable_type in [VariableTypeEnum.integer, VariableTypeEnum.binary] ], } self.n_points = n_points self.evaluator = evaluator self.rng = np.random.default_rng(seed) self.seed = seed def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out tmp = { var.symbol: self.rng.integers( low=var.lowerbound, high=var.upperbound, size=self.n_points, endpoint=True ).astype(dtype=float) if var.variable_type in [VariableTypeEnum.binary, VariableTypeEnum.integer] else self.rng.uniform(low=var.lowerbound, high=var.upperbound, size=self.n_points).astype(dtype=float) for var in self.problem.variables } # combine # self.population self.population = pl.DataFrame(tmp) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out def update(self, message) -> None: """Update the generator based on the message.""" ``` ##### __init__ ``` __init__( problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher, ) ``` Initialize the RandomMixedIntegerGenerator class. Parameters: | Name | Type | Description | Default | | ----------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem to solve. | *required* | | `evaluator` | `BaseEvaluator` | The evaluator to evaluate the population. | *required* | | `n_points` | `int` | The number of points to generate for the initial population. | *required* | | `seed` | `int` | The seed for the random number generator. | *required* | | `verbosity` | `int` | The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. | *required* | | `publisher` | `Publisher` | The publisher to publish the messages. | *required* | Source code in `desdeo/emo/operators/generator.py` ``` def __init__( self, problem: Problem, evaluator: EMOEvaluator, n_points: int, seed: int, verbosity: int, publisher: Publisher ): """Initialize the RandomMixedIntegerGenerator class. Args: problem (Problem): The problem to solve. evaluator (BaseEvaluator): The evaluator to evaluate the population. n_points (int): The number of points to generate for the initial population. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the generator. A verbosity of 2 is needed if you want to maintain an external archive. Otherwise, a verbosity of 1 is sufficient. publisher (Publisher): The publisher to publish the messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.var_symbol_types = { VariableTypeEnum.real: [ var.symbol for var in problem.variables if var.variable_type == VariableTypeEnum.real ], VariableTypeEnum.integer: [ var.symbol for var in problem.variables if var.variable_type in [VariableTypeEnum.integer, VariableTypeEnum.binary] ], } self.n_points = n_points self.evaluator = evaluator self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do() -> tuple[pl.DataFrame, pl.DataFrame] ``` Generate the initial population. Returns: | Type | Description | | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[DataFrame, DataFrame]` | tuple\[pl.DataFrame, pl.DataFrame\]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. | Source code in `desdeo/emo/operators/generator.py` ``` def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate the initial population. Returns: tuple[pl.DataFrame, pl.DataFrame]: The initial population as the first element, the corresponding objectives, the constraint violations, and the targets as the second element. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out tmp = { var.symbol: self.rng.integers( low=var.lowerbound, high=var.upperbound, size=self.n_points, endpoint=True ).astype(dtype=float) if var.variable_type in [VariableTypeEnum.binary, VariableTypeEnum.integer] else self.rng.uniform(low=var.lowerbound, high=var.upperbound, size=self.n_points).astype(dtype=float) for var in self.problem.variables } # combine # self.population self.population = pl.DataFrame(tmp) self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out ``` ##### update ``` update(message) -> None ``` Update the generator based on the message. Source code in `desdeo/emo/operators/generator.py` ``` def update(self, message) -> None: """Update the generator based on the message.""" ``` #### SeededHybridGenerator Bases: `BaseGenerator` Generates an initial population using a mix of seeded, perturbed, and random solutions. Source code in `desdeo/emo/operators/generator.py` ``` class SeededHybridGenerator(BaseGenerator): """Generates an initial population using a mix of seeded, perturbed, and random solutions.""" def __init__( self, problem, evaluator, publisher, verbosity, seed: int, n_points: int, seed_solution: pl.DataFrame, perturb_fraction: float = 0.2, sigma: float = 0.02, flip_prob: float = 0.1, ): """Initialize the seeded hybrid generator. The generator always includes the provided seed solution in the initial population, fills a fraction of the population with small perturbations around the seed, and fills the remainder with randomly generated solutions. Args: problem (Problem): The optimization problem. evaluator (EMOEvaluator): Evaluator used to compute objectives and constraints. publisher (Publisher): Publisher used for emitting generator messages. verbosity (int): Verbosity level of the generator. seed (int): Seed used for random number generation. n_points (int): Total size of the initial population. seed_solution (pl.DataFrame): A single-row DataFrame containing a seed decision variable vector. perturb_fraction (float, optional): Fraction of the population generated by perturbing the seed solution. Defaults to 0.2. sigma (float, optional): Relative perturbation scale with respect to variable ranges. Defaults to 0.02. flip_prob (float, optional): Probability of flipping a binary variable when perturbing the seed. Defaults to 0.1. Raises: TypeError: If ``seed_solution`` is not a polars DataFrame. ValueError: If ``seed_solution`` does not contain exactly one row. ValueError: If ``seed_solution`` columns do not match problem variables. ValueError: If ``n_points`` is not positive. ValueError: If ``perturb_fraction`` is outside ``[0, 1]``. ValueError: If ``sigma`` is negative. ValueError: If ``flip_prob`` is outside ``[0, 1]``. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if not isinstance(seed_solution, pl.DataFrame): raise TypeError("seed_solution must be a polars DataFrame.") if seed_solution.shape[0] != 1: raise ValueError("seed_solution must have exactly one row.") if set(seed_solution.columns) != set(self.variable_symbols): raise ValueError("seed_solution columns must match problem variables.") if n_points <= 0: raise ValueError("n_points must be > 0.") if not (0.0 <= perturb_fraction <= 1.0): raise ValueError("perturb_fraction must be in [0, 1].") if sigma < 0: raise ValueError("sigma must be >= 0.") if not (0.0 <= flip_prob <= 1.0): raise ValueError("flip_prob must be in [0, 1].") self.n_points = n_points self.seed_solution = seed_solution self.perturb_fraction = perturb_fraction self.sigma = sigma self.flip_prob = flip_prob self.evaluator = evaluator self.seed = seed self.rng = np.random.default_rng(self.seed) self.population = None self.out = None def _random_population(self, n: int) -> pl.DataFrame: tmp = {} for var in self.problem.variables: if var.variable_type in [VariableTypeEnum.binary, VariableTypeEnum.integer]: vals = self.rng.integers(var.lowerbound, var.upperbound, size=n, endpoint=True).astype(float) else: vals = self.rng.uniform(var.lowerbound, var.upperbound, size=n).astype(float) tmp[var.symbol] = vals return pl.DataFrame(tmp) def _perturb_seed(self, n: int) -> pl.DataFrame: # includes the exact seed as first row seed_row = self.seed_solution.select(self.variable_symbols).to_dict(as_series=False) seed_vals = {k: float(v[0]) for k, v in seed_row.items()} rows = [seed_vals] # ensure seed present if n <= 1: return pl.DataFrame(rows) for _ in range(n - 1): x = {} for var in self.problem.variables: lb, ub = float(var.lowerbound), float(var.upperbound) r = ub - lb v0 = seed_vals[var.symbol] if var.variable_type == VariableTypeEnum.binary: v = 1.0 - v0 if self.rng.random() < self.flip_prob else v0 elif var.variable_type == VariableTypeEnum.integer: # scales integer nose step = max(1, round(self.sigma * r)) if r >= 1 else 0 dv = self.rng.integers(-step, step + 1) if step > 0 else 0 v = float(int(np.clip(round(v0 + dv), lb, ub))) else: # continuous noise is proportional to range dv = self.rng.normal(0.0, self.sigma * r if r > 0 else 0.0) v = float(np.clip(v0 + dv, lb, ub)) x[var.symbol] = v rows.append(x) return pl.DataFrame(rows) def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate a population. Returns: tuple[pl.DataFrame, pl.DataFrame]: the population. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out n_pert = max(1, round(self.perturb_fraction * self.n_points)) n_pert = min(n_pert, self.n_points) n_rand = self.n_points - n_pert pert = self._perturb_seed(n_pert) rand = self._random_population(n_rand) if n_rand > 0 else pl.DataFrame({s: [] for s in self.variable_symbols}) self.population = pl.concat([pert, rand], how="vertical") self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out def update(self, message) -> None: """Update the generator based on the message.""" ``` ##### __init__ ``` __init__( problem, evaluator, publisher, verbosity, seed: int, n_points: int, seed_solution: DataFrame, perturb_fraction: float = 0.2, sigma: float = 0.02, flip_prob: float = 0.1, ) ``` Initialize the seeded hybrid generator. The generator always includes the provided seed solution in the initial population, fills a fraction of the population with small perturbations around the seed, and fills the remainder with randomly generated solutions. Parameters: | Name | Type | Description | Default | | ------------------ | -------------- | -------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The optimization problem. | *required* | | `evaluator` | `EMOEvaluator` | Evaluator used to compute objectives and constraints. | *required* | | `publisher` | `Publisher` | Publisher used for emitting generator messages. | *required* | | `verbosity` | `int` | Verbosity level of the generator. | *required* | | `seed` | `int` | Seed used for random number generation. | *required* | | `n_points` | `int` | Total size of the initial population. | *required* | | `seed_solution` | `DataFrame` | A single-row DataFrame containing a seed decision variable vector. | *required* | | `perturb_fraction` | `float` | Fraction of the population generated by perturbing the seed solution. Defaults to 0.2. | `0.2` | | `sigma` | `float` | Relative perturbation scale with respect to variable ranges. Defaults to 0.02. | `0.02` | | `flip_prob` | `float` | Probability of flipping a binary variable when perturbing the seed. Defaults to 0.1. | `0.1` | Raises: | Type | Description | | ------------ | -------------------------------------------------------- | | `TypeError` | If seed_solution is not a polars DataFrame. | | `ValueError` | If seed_solution does not contain exactly one row. | | `ValueError` | If seed_solution columns do not match problem variables. | | `ValueError` | If n_points is not positive. | | `ValueError` | If perturb_fraction is outside [0, 1]. | | `ValueError` | If sigma is negative. | | `ValueError` | If flip_prob is outside [0, 1]. | Source code in `desdeo/emo/operators/generator.py` ``` def __init__( self, problem, evaluator, publisher, verbosity, seed: int, n_points: int, seed_solution: pl.DataFrame, perturb_fraction: float = 0.2, sigma: float = 0.02, flip_prob: float = 0.1, ): """Initialize the seeded hybrid generator. The generator always includes the provided seed solution in the initial population, fills a fraction of the population with small perturbations around the seed, and fills the remainder with randomly generated solutions. Args: problem (Problem): The optimization problem. evaluator (EMOEvaluator): Evaluator used to compute objectives and constraints. publisher (Publisher): Publisher used for emitting generator messages. verbosity (int): Verbosity level of the generator. seed (int): Seed used for random number generation. n_points (int): Total size of the initial population. seed_solution (pl.DataFrame): A single-row DataFrame containing a seed decision variable vector. perturb_fraction (float, optional): Fraction of the population generated by perturbing the seed solution. Defaults to 0.2. sigma (float, optional): Relative perturbation scale with respect to variable ranges. Defaults to 0.02. flip_prob (float, optional): Probability of flipping a binary variable when perturbing the seed. Defaults to 0.1. Raises: TypeError: If ``seed_solution`` is not a polars DataFrame. ValueError: If ``seed_solution`` does not contain exactly one row. ValueError: If ``seed_solution`` columns do not match problem variables. ValueError: If ``n_points`` is not positive. ValueError: If ``perturb_fraction`` is outside ``[0, 1]``. ValueError: If ``sigma`` is negative. ValueError: If ``flip_prob`` is outside ``[0, 1]``. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if not isinstance(seed_solution, pl.DataFrame): raise TypeError("seed_solution must be a polars DataFrame.") if seed_solution.shape[0] != 1: raise ValueError("seed_solution must have exactly one row.") if set(seed_solution.columns) != set(self.variable_symbols): raise ValueError("seed_solution columns must match problem variables.") if n_points <= 0: raise ValueError("n_points must be > 0.") if not (0.0 <= perturb_fraction <= 1.0): raise ValueError("perturb_fraction must be in [0, 1].") if sigma < 0: raise ValueError("sigma must be >= 0.") if not (0.0 <= flip_prob <= 1.0): raise ValueError("flip_prob must be in [0, 1].") self.n_points = n_points self.seed_solution = seed_solution self.perturb_fraction = perturb_fraction self.sigma = sigma self.flip_prob = flip_prob self.evaluator = evaluator self.seed = seed self.rng = np.random.default_rng(self.seed) self.population = None self.out = None ``` ##### do ``` do() -> tuple[pl.DataFrame, pl.DataFrame] ``` Generate a population. Returns: | Type | Description | | ----------------------------- | ---------------------------------------------------- | | `tuple[DataFrame, DataFrame]` | tuple\[pl.DataFrame, pl.DataFrame\]: the population. | Source code in `desdeo/emo/operators/generator.py` ``` def do(self) -> tuple[pl.DataFrame, pl.DataFrame]: """Generate a population. Returns: tuple[pl.DataFrame, pl.DataFrame]: the population. """ if self.population is not None and self.out is not None: self.notify() return self.population, self.out n_pert = max(1, round(self.perturb_fraction * self.n_points)) n_pert = min(n_pert, self.n_points) n_rand = self.n_points - n_pert pert = self._perturb_seed(n_pert) rand = self._random_population(n_rand) if n_rand > 0 else pl.DataFrame({s: [] for s in self.variable_symbols}) self.population = pl.concat([pert, rand], how="vertical") self.out = self.evaluator.evaluate(self.population) self.notify() return self.population, self.out ``` ##### update ``` update(message) -> None ``` Update the generator based on the message. Source code in `desdeo/emo/operators/generator.py` ``` def update(self, message) -> None: """Update the generator based on the message.""" ``` ## Evaluator ### desdeo.emo.operators.evaluator Classes for evaluating the objectives and constraints of the individuals in the population. #### EMOEvaluator Bases: `Subscriber` Base class for evaluating the objectives and constraints of the individuals in the population. This class should be inherited by the classes that implement the evaluation of the objectives and constraints of the individuals in the population. Source code in `desdeo/emo/operators/evaluator.py` ``` class EMOEvaluator(Subscriber): """Base class for evaluating the objectives and constraints of the individuals in the population. This class should be inherited by the classes that implement the evaluation of the objectives and constraints of the individuals in the population. """ @property def provided_topics(self) -> dict[int, Sequence[EvaluatorMessageTopics]]: """The topics provided by the Evaluator.""" return { 0: [], 1: [EvaluatorMessageTopics.NEW_EVALUATIONS], 2: [ EvaluatorMessageTopics.NEW_EVALUATIONS, EvaluatorMessageTopics.VERBOSE_OUTPUTS, ], } @property def interested_topics(self): """The topics that the Evaluator is interested in.""" return [] def __init__(self, problem: Problem, verbosity: int, publisher: Publisher): """Initialize the EMOEvaluator class.""" super().__init__( verbosity=verbosity, publisher=publisher, ) self.problem = problem # Build the underlying evaluator once. Constructing it per call re-ran its setup on every # generation, and for a problem with surrogate objectives that setup is a joblib.load of # every surrogate from disk -- roughly 0.6 s per model per generation. self._simulator_evaluator = SimulatorEvaluator(problem) self._flattened_variable_symbols = [name.symbol for name in problem.get_flattened_variables()] self.variable_symbols = [name.symbol for name in problem.variables] self.population: pl.DataFrame self.out: pl.DataFrame self.new_evals: int = 0 def evaluate(self, population: pl.DataFrame) -> pl.DataFrame: """Evaluate and return the objectives. Args: population (pl.Dataframe): The set of decision variables to evaluate. Returns: pl.Dataframe: A dataframe of objective vectors, target vectors, and constraint vectors. """ self.population = population out = self._simulator_evaluator.evaluate( {symbol: population[symbol].to_list() for symbol in self._flattened_variable_symbols}, flat=True, ) # remove variable_symbols from the output self.out = out.drop(self.variable_symbols, strict=False) self.new_evals = len(population) # merge the objectives and targets self.notify() return self.out def state(self) -> Sequence[Message]: """The state of the evaluator sent to the Publisher.""" if self.population is None or self.out is None or self.population is None or self.verbosity == 0: return [] if self.verbosity == 1: return [ IntMessage( topic=EvaluatorMessageTopics.NEW_EVALUATIONS, value=self.new_evals, source=self.__class__.__name__, ) ] if isinstance(self.population, pl.DataFrame): message = PolarsDataFrameMessage( topic=EvaluatorMessageTopics.VERBOSE_OUTPUTS, value=self.population.hstack(self.out), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=EvaluatorMessageTopics.VERBOSE_OUTPUTS, value=self.out, source=self.__class__.__name__, ) return [ IntMessage( topic=EvaluatorMessageTopics.NEW_EVALUATIONS, value=self.new_evals, source=self.__class__.__name__, ), message, ] def update(self, *_, **__): """Update the parameters of the evaluator.""" ``` ##### interested_topics ``` interested_topics ``` The topics that the Evaluator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[EvaluatorMessageTopics]] ``` The topics provided by the Evaluator. ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher ) ``` Initialize the EMOEvaluator class. Source code in `desdeo/emo/operators/evaluator.py` ``` def __init__(self, problem: Problem, verbosity: int, publisher: Publisher): """Initialize the EMOEvaluator class.""" super().__init__( verbosity=verbosity, publisher=publisher, ) self.problem = problem # Build the underlying evaluator once. Constructing it per call re-ran its setup on every # generation, and for a problem with surrogate objectives that setup is a joblib.load of # every surrogate from disk -- roughly 0.6 s per model per generation. self._simulator_evaluator = SimulatorEvaluator(problem) self._flattened_variable_symbols = [name.symbol for name in problem.get_flattened_variables()] self.variable_symbols = [name.symbol for name in problem.variables] self.population: pl.DataFrame self.out: pl.DataFrame self.new_evals: int = 0 ``` ##### evaluate ``` evaluate(population: DataFrame) -> pl.DataFrame ``` Evaluate and return the objectives. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------ | ---------- | | `population` | `Dataframe` | The set of decision variables to evaluate. | *required* | Returns: | Type | Description | | ----------- | --------------------------------------------------------------------------------------- | | `DataFrame` | pl.Dataframe: A dataframe of objective vectors, target vectors, and constraint vectors. | Source code in `desdeo/emo/operators/evaluator.py` ``` def evaluate(self, population: pl.DataFrame) -> pl.DataFrame: """Evaluate and return the objectives. Args: population (pl.Dataframe): The set of decision variables to evaluate. Returns: pl.Dataframe: A dataframe of objective vectors, target vectors, and constraint vectors. """ self.population = population out = self._simulator_evaluator.evaluate( {symbol: population[symbol].to_list() for symbol in self._flattened_variable_symbols}, flat=True, ) # remove variable_symbols from the output self.out = out.drop(self.variable_symbols, strict=False) self.new_evals = len(population) # merge the objectives and targets self.notify() return self.out ``` ##### state ``` state() -> Sequence[Message] ``` The state of the evaluator sent to the Publisher. Source code in `desdeo/emo/operators/evaluator.py` ``` def state(self) -> Sequence[Message]: """The state of the evaluator sent to the Publisher.""" if self.population is None or self.out is None or self.population is None or self.verbosity == 0: return [] if self.verbosity == 1: return [ IntMessage( topic=EvaluatorMessageTopics.NEW_EVALUATIONS, value=self.new_evals, source=self.__class__.__name__, ) ] if isinstance(self.population, pl.DataFrame): message = PolarsDataFrameMessage( topic=EvaluatorMessageTopics.VERBOSE_OUTPUTS, value=self.population.hstack(self.out), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=EvaluatorMessageTopics.VERBOSE_OUTPUTS, value=self.out, source=self.__class__.__name__, ) return [ IntMessage( topic=EvaluatorMessageTopics.NEW_EVALUATIONS, value=self.new_evals, source=self.__class__.__name__, ), message, ] ``` ##### update ``` update(*_, **__) ``` Update the parameters of the evaluator. Source code in `desdeo/emo/operators/evaluator.py` ``` def update(self, *_, **__): """Update the parameters of the evaluator.""" ``` ## Crossover operators ### desdeo.emo.operators.crossover Evolutionary operators for recombination. Various evolutionary operators for recombination in multiobjective optimization are defined here. #### BaseCrossover Bases: `Subscriber` A base class for crossover operators. Source code in `desdeo/emo/operators/crossover.py` ``` class BaseCrossover(Subscriber): """A base class for crossover operators.""" def __init__(self, problem: Problem, verbosity: int, publisher: Publisher, seed: int): """Initialize a crossover operator.""" super().__init__(verbosity=verbosity, publisher=publisher) self.problem = problem self.variable_symbols = [var.symbol for var in problem.get_flattened_variables()] self.lower_bounds = [var.lowerbound for var in problem.get_flattened_variables()] self.upper_bounds = [var.upperbound for var in problem.get_flattened_variables()] self.variable_types = [var.variable_type for var in problem.get_flattened_variables()] self.variable_combination: VariableDomainTypeEnum = problem.variable_domain # Populated by `do`. Initialized here so that `state` can be called before the first # crossover, e.g. by a logger that reports the operator's state up front. self.parent_population: pl.DataFrame | None = None self.offspring_population: pl.DataFrame | None = None self.rng = np.random.default_rng(seed) self.seed = seed # TODO(@light-weaver): The row order of the offspring returned by `do` is not consistent across # operators. Most of them build the two children separately and `np.vstack` them, so the output is # all first-children followed by all second-children; SimulatedBinaryCrossover.unbounded_offsprings # and LocalCrossover instead write offspring[i] / offspring[i+1] in place, so their children are # interleaved. Row i of the output is therefore not reliably the child of parent i, which makes it # impossible to trace lineage generically. Worth unifying on one convention and documenting it here. @abstractmethod def do(self, *, population: pl.DataFrame, to_mate: list[int] | None = None) -> pl.DataFrame: """Perform the crossover operation. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ def get_parents(self, population: pl.DataFrame, to_mate: list[int] | None = None) -> pl.DataFrame: """Just get the relevant parents from the population and set the parent population. Note: `DataFrame.to_numpy` hands back an F-contiguous array, and `np.zeros_like` preserves that order. Every `pl.from_numpy` in this module therefore states `orient="row"`: for a square offspring block (as many offspring as variables) polars cannot infer the orientation from the shape, and would read such an array column-wise, transposing it. """ pop_size = population.shape[0] if to_mate is None: shuffled_ids = list(range(pop_size)) self.rng.shuffle(shuffled_ids) else: shuffled_ids = copy.copy(to_mate) if len(shuffled_ids) % 2 == 1: shuffled_ids.append(shuffled_ids[0]) self.parent_population = population[shuffled_ids] return self.parent_population ``` ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, seed: int, ) ``` Initialize a crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def __init__(self, problem: Problem, verbosity: int, publisher: Publisher, seed: int): """Initialize a crossover operator.""" super().__init__(verbosity=verbosity, publisher=publisher) self.problem = problem self.variable_symbols = [var.symbol for var in problem.get_flattened_variables()] self.lower_bounds = [var.lowerbound for var in problem.get_flattened_variables()] self.upper_bounds = [var.upperbound for var in problem.get_flattened_variables()] self.variable_types = [var.variable_type for var in problem.get_flattened_variables()] self.variable_combination: VariableDomainTypeEnum = problem.variable_domain # Populated by `do`. Initialized here so that `state` can be called before the first # crossover, e.g. by a logger that reports the operator's state up front. self.parent_population: pl.DataFrame | None = None self.offspring_population: pl.DataFrame | None = None self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform the crossover operation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | --------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` @abstractmethod def do(self, *, population: pl.DataFrame, to_mate: list[int] | None = None) -> pl.DataFrame: """Perform the crossover operation. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ ``` ##### get_parents ``` get_parents( population: DataFrame, to_mate: list[int] | None = None ) -> pl.DataFrame ``` Just get the relevant parents from the population and set the parent population. Note `DataFrame.to_numpy` hands back an F-contiguous array, and `np.zeros_like` preserves that order. Every `pl.from_numpy` in this module therefore states `orient="row"`: for a square offspring block (as many offspring as variables) polars cannot infer the orientation from the shape, and would read such an array column-wise, transposing it. Source code in `desdeo/emo/operators/crossover.py` ``` def get_parents(self, population: pl.DataFrame, to_mate: list[int] | None = None) -> pl.DataFrame: """Just get the relevant parents from the population and set the parent population. Note: `DataFrame.to_numpy` hands back an F-contiguous array, and `np.zeros_like` preserves that order. Every `pl.from_numpy` in this module therefore states `orient="row"`: for a square offspring block (as many offspring as variables) polars cannot infer the orientation from the shape, and would read such an array column-wise, transposing it. """ pop_size = population.shape[0] if to_mate is None: shuffled_ids = list(range(pop_size)) self.rng.shuffle(shuffled_ids) else: shuffled_ids = copy.copy(to_mate) if len(shuffled_ids) % 2 == 1: shuffled_ids.append(shuffled_ids[0]) self.parent_population = population[shuffled_ids] return self.parent_population ``` #### BlendAlphaCrossover Bases: `BaseCrossover` Blend-alpha (BLX-alpha) crossover for continuous problems. Each offspring component is drawn uniformly from the interval spanned by the two parent components, widened on both sides by `alpha` times that span and clipped to the variable bounds. References Eshelman, L. J., & Schaffer, J. D. (1993). Real-coded genetic algorithms and interval-schemata. In L. D. Whitley (Ed.), Foundations of Genetic Algorithms (Vol. 2, pp. 187-202). Elsevier. https://doi.org/10.1016/B978-0-08-094832-4.50018-0 Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 Source code in `desdeo/emo/operators/crossover.py` ``` class BlendAlphaCrossover(BaseCrossover): """Blend-alpha (BLX-alpha) crossover for continuous problems. Each offspring component is drawn uniformly from the interval spanned by the two parent components, widened on both sides by `alpha` times that span and clipped to the variable bounds. References: Eshelman, L. J., & Schaffer, J. D. (1993). Real-coded genetic algorithms and interval-schemata. In L. D. Whitley (Ed.), Foundations of Genetic Algorithms (Vol. 2, pp. 187-202). Elsevier. https://doi.org/10.1016/B978-0-08-094832-4.50018-0 Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 """ @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the blend alpha crossover operator. Note: The operator has no crossover probability, so it does not provide that topic. """ return { 0: [], 1: [ CrossoverMessageTopics.ALPHA, ], 2: [ CrossoverMessageTopics.ALPHA, CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics provided by the blend alpha crossover operator.""" return [] def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, alpha: float = 0.5, repeats: int = 2, sample_each_component: bool = True, ): """Initialize the blend alpha crossover operator. Details here: Eshelman, L. J., & Schaffer, J. D. (1993). Real-Coded Genetic Algorithms and Interval-Schemata. In L. D. Whitley (Ed.), Foundations of Genetic Algorithms (Vol. 2, pp. 187-202). Elsevier. https://doi.org/10.1016/B978-0-08-094832-4.50018-0 Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): the seed used in the random number generator for choosing the crossover point. alpha (float, optional): non-negative blending factor 'alpha' that controls the extent to which offspring may be sampled outside the interval defined by each pair of parent genes. alpha = 0 restricts children strictly within the parents range, larger alpha allows outliers. Defaults to 0.5. repeats (int, optional): the number of times to repeat the crossover operation for a given pair of parents. Defaults to 2. Note that a value of 1 means that only one child will be generated for each pair of parents. sample_each_component (bool, optional): whether to sample each component of the offspring independently. If `True`, a new random number is generated for each component of the offspring. If `False`, a single random number is generated for the entire offspring. Defaults to `True`. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("BlendAlphaCrossover only works on continuous problems.") if alpha < 0: raise ValueError("Alpha must be non-negative.") self.alpha = alpha self.repeats = repeats self.sample_each_component = sample_each_component def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform BLX-alpha crossover _correctly_. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy() mating_pop_size = mating_pop.shape[0] original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] num_var = mating_pop.shape[1] offspring_size = mating_pop_size / 2 * self.repeats offsprings = np.zeros((int(offspring_size), num_var)) if self.sample_each_component: offspring_randoms = self.rng.random((int(offspring_size), num_var)) else: offspring_randoms = self.rng.random((int(offspring_size), 1)) for i in range(0, mating_pop_size, 2): p1 = mating_pop[i] p2 = mating_pop[i + 1] c_min = np.minimum(p1, p2) c_max = np.maximum(p1, p2) span = c_max - c_min lower = c_min - self.alpha * span upper = c_max + self.alpha * span lower = np.maximum(lower, self.lower_bounds) upper = np.minimum(upper, self.upper_bounds) for j in range(self.repeats): idx = (i // 2) * self.repeats + j offsprings[idx] = lower + offspring_randoms[idx] * (upper - lower) # An odd sized mating pool was padded with a duplicate parent, so the final pair produced a # full extra set of `repeats` offspring. Keep only as many as the unpadded pool would have # produced. Dropping a single row unconditionally is only correct when `repeats` is 2. if original_pop_size % 2 == 1: offsprings = offsprings[: (original_pop_size * self.repeats + 1) // 2, :] self.offspring_population = pl.from_numpy(offsprings, schema=self.variable_symbols, orient="row") self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the blend-alpha crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 1: msgs.append( FloatMessage( topic=CrossoverMessageTopics.ALPHA, source=self.__class__.__name__, value=self.alpha, ) ) if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### interested_topics ``` interested_topics ``` The message topics provided by the blend alpha crossover operator. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the blend alpha crossover operator. Note The operator has no crossover probability, so it does not provide that topic. ##### __init__ ``` __init__( *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, alpha: float = 0.5, repeats: int = 2, sample_each_component: bool = True, ) ``` Initialize the blend alpha crossover operator. Details here: Eshelman, L. J., & Schaffer, J. D. (1993). Real-Coded Genetic Algorithms and Interval-Schemata. In L. D. Whitley (Ed.), Foundations of Genetic Algorithms (Vol. 2, pp. 187-202). Elsevier. https://doi.org/10.1016/B978-0-08-094832-4.50018-0 Parameters: | Name | Type | Description | Default | | ----------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | | `seed` | `int` | the seed used in the random number generator for choosing the crossover point. | *required* | | `alpha` | `float` | non-negative blending factor 'alpha' that controls the extent to which offspring may be sampled outside the interval defined by each pair of parent genes. alpha = 0 restricts children strictly within the parents range, larger alpha allows outliers. Defaults to 0.5. | `0.5` | | `repeats` | `int` | the number of times to repeat the crossover operation for a given pair of parents. Defaults to 2. Note that a value of 1 means that only one child will be generated for each pair of parents. | `2` | | `sample_each_component` | `bool` | whether to sample each component of the offspring independently. If True, a new random number is generated for each component of the offspring. If False, a single random number is generated for the entire offspring. Defaults to True. | `True` | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, alpha: float = 0.5, repeats: int = 2, sample_each_component: bool = True, ): """Initialize the blend alpha crossover operator. Details here: Eshelman, L. J., & Schaffer, J. D. (1993). Real-Coded Genetic Algorithms and Interval-Schemata. In L. D. Whitley (Ed.), Foundations of Genetic Algorithms (Vol. 2, pp. 187-202). Elsevier. https://doi.org/10.1016/B978-0-08-094832-4.50018-0 Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): the seed used in the random number generator for choosing the crossover point. alpha (float, optional): non-negative blending factor 'alpha' that controls the extent to which offspring may be sampled outside the interval defined by each pair of parent genes. alpha = 0 restricts children strictly within the parents range, larger alpha allows outliers. Defaults to 0.5. repeats (int, optional): the number of times to repeat the crossover operation for a given pair of parents. Defaults to 2. Note that a value of 1 means that only one child will be generated for each pair of parents. sample_each_component (bool, optional): whether to sample each component of the offspring independently. If `True`, a new random number is generated for each component of the offspring. If `False`, a single random number is generated for the entire offspring. Defaults to `True`. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("BlendAlphaCrossover only works on continuous problems.") if alpha < 0: raise ValueError("Alpha must be non-negative.") self.alpha = alpha self.repeats = repeats self.sample_each_component = sample_each_component ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform BLX-alpha crossover *correctly*. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | --------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform BLX-alpha crossover _correctly_. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy() mating_pop_size = mating_pop.shape[0] original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] num_var = mating_pop.shape[1] offspring_size = mating_pop_size / 2 * self.repeats offsprings = np.zeros((int(offspring_size), num_var)) if self.sample_each_component: offspring_randoms = self.rng.random((int(offspring_size), num_var)) else: offspring_randoms = self.rng.random((int(offspring_size), 1)) for i in range(0, mating_pop_size, 2): p1 = mating_pop[i] p2 = mating_pop[i + 1] c_min = np.minimum(p1, p2) c_max = np.maximum(p1, p2) span = c_max - c_min lower = c_min - self.alpha * span upper = c_max + self.alpha * span lower = np.maximum(lower, self.lower_bounds) upper = np.minimum(upper, self.upper_bounds) for j in range(self.repeats): idx = (i // 2) * self.repeats + j offsprings[idx] = lower + offspring_randoms[idx] * (upper - lower) # An odd sized mating pool was padded with a duplicate parent, so the final pair produced a # full extra set of `repeats` offspring. Keep only as many as the unpadded pool would have # produced. Dropping a single row unconditionally is only correct when `repeats` is 2. if original_pop_size % 2 == 1: offsprings = offsprings[: (original_pop_size * self.repeats + 1) // 2, :] self.offspring_population = pl.from_numpy(offsprings, schema=self.variable_symbols, orient="row") self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the blend-alpha crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the blend-alpha crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 1: msgs.append( FloatMessage( topic=CrossoverMessageTopics.ALPHA, source=self.__class__.__name__, value=self.alpha, ) ) if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### BoundedExponentialCrossover Bases: `BaseCrossover` Bounded-exponential (BEX) crossover for continuous problems. A parent centric operator: each offspring is displaced from its own parent by a bounded exponential deviate whose scale is `lambda_` times the separation of the parents, truncated so that no offspring can fall outside the variable bounds. It is the bounded refinement of the Laplace crossover (LX) of Deep and Thakur, which has no such guarantee. The reference derives the offspring under the assumption that the first parent holds the smaller value, and leaves the mirrored case to the reader; `do` implements that mirrored case, since a mating pool is unordered. References Thakur, M., Meghwani, S. S., & Jalota, H. (2014). A modified real coded genetic algorithm for constrained optimization. Applied Mathematics and Computation, 235, 292-317. https://doi.org/10.1016/j.amc.2014.02.093 Deep, K., & Thakur, M. (2007). A new crossover operator for real coded genetic algorithms. Applied Mathematics and Computation, 188(1), 895-911. (The Laplace crossover that BEX modifies.) Source code in `desdeo/emo/operators/crossover.py` ``` class BoundedExponentialCrossover(BaseCrossover): """Bounded-exponential (BEX) crossover for continuous problems. A parent centric operator: each offspring is displaced from its own parent by a bounded exponential deviate whose scale is `lambda_` times the separation of the parents, truncated so that no offspring can fall outside the variable bounds. It is the bounded refinement of the Laplace crossover (LX) of Deep and Thakur, which has no such guarantee. The reference derives the offspring under the assumption that the first parent holds the smaller value, and leaves the mirrored case to the reader; `do` implements that mirrored case, since a mating pool is unordered. References: Thakur, M., Meghwani, S. S., & Jalota, H. (2014). A modified real coded genetic algorithm for constrained optimization. Applied Mathematics and Computation, 235, 292-317. https://doi.org/10.1016/j.amc.2014.02.093 Deep, K., & Thakur, M. (2007). A new crossover operator for real coded genetic algorithms. Applied Mathematics and Computation, 188(1), 895-911. (The Laplace crossover that BEX modifies.) """ @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the bounded exponential crossover operator.""" return { 0: [], 1: [ CrossoverMessageTopics.XOVER_PROBABILITY, CrossoverMessageTopics.LAMBDA, ], 2: [ CrossoverMessageTopics.XOVER_PROBABILITY, CrossoverMessageTopics.LAMBDA, CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics provided by the bounded exponential crossover operator.""" return [] def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, lambda_: float = 0.1, xover_probability: float = 1.0, uniform_xover_probability: float = 0.0, ): """Initialize the bounded-exponential crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): random seed for the internal generator. lambda_ (float, optional): positive scale λ for the exponential distribution. Defaults to 0.1. Larger values produce more widely dispersed offspring, smaller values produce offspring closer to the parents. xover_probability (float, optional): probability of applying crossover to each pair. Defaults to 1.0. uniform_xover_probability (float, optional): per-variable probability that the two offspring exchange which parent they descend from. Defaults to 0.0, which is the operator's original behaviour: every offspring keeps its own parent's identity in every variable. At 0.5 the operator gains a uniform-crossover component, the same one `SimulatedBinaryCrossover` carries under this name. It matters there: on a 105-problem grid the two SBX arms that differ *only* in this parameter placed 10.9x apart in median IGD+ regret, 0.0061 at 0.5 against 0.0665 at 0.0. Whether BEX responds the same way is an open question, which is why the default preserves the existing behaviour rather than assuming the transfer. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("BoundedExponentialCrossover only works on continuous problems.") if lambda_ <= 0: raise ValueError("lambda_ must be positive.") if not 0 <= xover_probability <= 1: raise ValueError("xover_probability must be in [0,1].") if not 0 <= uniform_xover_probability <= 1: raise ValueError("uniform_xover_probability must be in [0,1].") self.lambda_ = lambda_ self.xover_probability = xover_probability self.uniform_xover_probability = uniform_xover_probability def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform bounded-exponential crossover. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy() mating_pop_size = mating_pop.shape[0] num_var = mating_pop.shape[1] original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] x_lower = np.array(self.lower_bounds) x_upper = np.array(self.upper_bounds) # The absolute separation |y_i - x_i| of the parents, which sets the scale of the # exponential. The reference derives beta under the stated assumption x_i < y_i and leaves # the mirrored case to the reader, but a mating pool is unordered, so both orderings occur # about equally often per decision variable. Using the *signed* difference flips the sign of # every exponent argument whenever x_i > y_i, which inverts the exponential: the density then # grows towards the truncation point instead of decaying away from the parent, so this parent # centric operator turns into a bound seeking one for roughly half of all variables. The # absolute separation is exactly the reference's mirrored case, and leaves the already # correct x_i < y_i ordering untouched. span = np.abs(parents2 - parents1) # Where the two parents share a value the span is zero and the offspring can only take that # same value, since every child is parent + beta * span. The exponent arguments below would # then divide by zero: harmless inf when the shared value is strictly inside the bounds, but # 0/0 -> nan when it sits exactly *on* a bound, which used to leak NaN decision variables # into the population (duplicate parents and bound-hugging variables are both common). Feed # the exponents a dummy span of one so that beta stays finite; multiplying by the true zero # span afterwards restores the parent value exactly. zero_span = span == 0 safe_span = np.where(zero_span, 1.0, span) u_i = self.rng.random((mating_pop_size // 2, num_var)) r_i = self.rng.random((mating_pop_size // 2, num_var)) # Both branches of each np.where below are evaluated eagerly; the unused branch can legitimately # overflow or divide by zero, producing inf/nan that np.where discards. # Silence the resulting benign numpy floating-point warnings. with np.errstate(divide="ignore", over="ignore", invalid="ignore"): exp_lower_1 = np.exp((x_lower - parents1) / (self.lambda_ * safe_span)) exp_upper_1 = np.exp((parents1 - x_upper) / (self.lambda_ * safe_span)) exp_lower_2 = np.exp((x_lower - parents2) / (self.lambda_ * safe_span)) exp_upper_2 = np.exp((parents2 - x_upper) / (self.lambda_ * safe_span)) beta_1 = np.where( r_i <= 0.5, # noqa: PLR2004 self.lambda_ * np.log(exp_lower_1 + u_i * (1 - exp_lower_1)), -self.lambda_ * np.log(1 - u_i * (1 - exp_upper_1)), ) beta_2 = np.where( r_i <= 0.5, # noqa: PLR2004 self.lambda_ * np.log(exp_lower_2 + u_i * (1 - exp_lower_2)), -self.lambda_ * np.log(1 - u_i * (1 - exp_upper_2)), ) # beta * span is already exactly zero wherever the span # is, but taking the parent value directly keeps a non-finite beta from reintroducing a NaN. offspring1 = np.where(zero_span, parents1, parents1 + beta_1 * span) offspring2 = np.where(zero_span, parents2, parents2 + beta_2 * span) # The uniform-crossover component, applied before the per-pair crossover probability so that # a pair which does not cross is returned as its parents untouched. # # Each BEX offspring is displaced from *its own* parent, so identity retention is structurally # 1.0: offspring one descends from parent one in every variable. Exchanging the two children's # values for a variable is what gives that variable to the other parent's line, and it is the # same operation `SimulatedBinaryCrossover` performs by flipping the sign of beta -- there the # two children sit symmetrically about the parent midpoint, so a sign flip swaps them exactly. if self.uniform_xover_probability > 0: swap = self.rng.random((mating_pop_size // 2, num_var)) <= self.uniform_xover_probability offspring1, offspring2 = ( np.where(swap, offspring2, offspring1), np.where(swap, offspring1, offspring2), ) mask = self.rng.random(mating_pop_size // 2) > self.xover_probability offspring1[mask, :] = parents1[mask, :] offspring2[mask, :] = parents2[mask, :] children = np.vstack((offspring1, offspring2)) if original_pop_size % 2 == 1: children = children[:-1, :] self.offspring_population = pl.from_numpy(children, schema=self.variable_symbols, orient="row").select( pl.all().cast(pl.Float64) ) self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 1: msgs.append( FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.xover_probability, ) ) msgs.append( FloatMessage( topic=CrossoverMessageTopics.LAMBDA, source=self.__class__.__name__, value=self.lambda_, ) ) if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### interested_topics ``` interested_topics ``` The message topics provided by the bounded exponential crossover operator. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the bounded exponential crossover operator. ##### __init__ ``` __init__( *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, lambda_: float = 0.1, xover_probability: float = 1.0, uniform_xover_probability: float = 0.0, ) ``` Initialize the bounded-exponential crossover operator. Parameters: | Name | Type | Description | Default | | --------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | | `seed` | `int` | random seed for the internal generator. | *required* | | `lambda_` | `float` | positive scale λ for the exponential distribution. Defaults to 0.1. Larger values produce more widely dispersed offspring, smaller values produce offspring closer to the parents. | `0.1` | | `xover_probability` | `float` | probability of applying crossover to each pair. Defaults to 1.0. | `1.0` | | `uniform_xover_probability` | `float` | per-variable probability that the two offspring exchange which parent they descend from. Defaults to 0.0, which is the operator's original behaviour: every offspring keeps its own parent's identity in every variable. At 0.5 the operator gains a uniform-crossover component, the same one SimulatedBinaryCrossover carries under this name. It matters there: on a 105-problem grid the two SBX arms that differ only in this parameter placed 10.9x apart in median IGD+ regret, 0.0061 at 0.5 against 0.0665 at 0.0. Whether BEX responds the same way is an open question, which is why the default preserves the existing behaviour rather than assuming the transfer. | `0.0` | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, lambda_: float = 0.1, xover_probability: float = 1.0, uniform_xover_probability: float = 0.0, ): """Initialize the bounded-exponential crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): random seed for the internal generator. lambda_ (float, optional): positive scale λ for the exponential distribution. Defaults to 0.1. Larger values produce more widely dispersed offspring, smaller values produce offspring closer to the parents. xover_probability (float, optional): probability of applying crossover to each pair. Defaults to 1.0. uniform_xover_probability (float, optional): per-variable probability that the two offspring exchange which parent they descend from. Defaults to 0.0, which is the operator's original behaviour: every offspring keeps its own parent's identity in every variable. At 0.5 the operator gains a uniform-crossover component, the same one `SimulatedBinaryCrossover` carries under this name. It matters there: on a 105-problem grid the two SBX arms that differ *only* in this parameter placed 10.9x apart in median IGD+ regret, 0.0061 at 0.5 against 0.0665 at 0.0. Whether BEX responds the same way is an open question, which is why the default preserves the existing behaviour rather than assuming the transfer. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("BoundedExponentialCrossover only works on continuous problems.") if lambda_ <= 0: raise ValueError("lambda_ must be positive.") if not 0 <= xover_probability <= 1: raise ValueError("xover_probability must be in [0,1].") if not 0 <= uniform_xover_probability <= 1: raise ValueError("uniform_xover_probability must be in [0,1].") self.lambda_ = lambda_ self.xover_probability = xover_probability self.uniform_xover_probability = uniform_xover_probability ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform bounded-exponential crossover. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | --------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform bounded-exponential crossover. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy() mating_pop_size = mating_pop.shape[0] num_var = mating_pop.shape[1] original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] x_lower = np.array(self.lower_bounds) x_upper = np.array(self.upper_bounds) # The absolute separation |y_i - x_i| of the parents, which sets the scale of the # exponential. The reference derives beta under the stated assumption x_i < y_i and leaves # the mirrored case to the reader, but a mating pool is unordered, so both orderings occur # about equally often per decision variable. Using the *signed* difference flips the sign of # every exponent argument whenever x_i > y_i, which inverts the exponential: the density then # grows towards the truncation point instead of decaying away from the parent, so this parent # centric operator turns into a bound seeking one for roughly half of all variables. The # absolute separation is exactly the reference's mirrored case, and leaves the already # correct x_i < y_i ordering untouched. span = np.abs(parents2 - parents1) # Where the two parents share a value the span is zero and the offspring can only take that # same value, since every child is parent + beta * span. The exponent arguments below would # then divide by zero: harmless inf when the shared value is strictly inside the bounds, but # 0/0 -> nan when it sits exactly *on* a bound, which used to leak NaN decision variables # into the population (duplicate parents and bound-hugging variables are both common). Feed # the exponents a dummy span of one so that beta stays finite; multiplying by the true zero # span afterwards restores the parent value exactly. zero_span = span == 0 safe_span = np.where(zero_span, 1.0, span) u_i = self.rng.random((mating_pop_size // 2, num_var)) r_i = self.rng.random((mating_pop_size // 2, num_var)) # Both branches of each np.where below are evaluated eagerly; the unused branch can legitimately # overflow or divide by zero, producing inf/nan that np.where discards. # Silence the resulting benign numpy floating-point warnings. with np.errstate(divide="ignore", over="ignore", invalid="ignore"): exp_lower_1 = np.exp((x_lower - parents1) / (self.lambda_ * safe_span)) exp_upper_1 = np.exp((parents1 - x_upper) / (self.lambda_ * safe_span)) exp_lower_2 = np.exp((x_lower - parents2) / (self.lambda_ * safe_span)) exp_upper_2 = np.exp((parents2 - x_upper) / (self.lambda_ * safe_span)) beta_1 = np.where( r_i <= 0.5, # noqa: PLR2004 self.lambda_ * np.log(exp_lower_1 + u_i * (1 - exp_lower_1)), -self.lambda_ * np.log(1 - u_i * (1 - exp_upper_1)), ) beta_2 = np.where( r_i <= 0.5, # noqa: PLR2004 self.lambda_ * np.log(exp_lower_2 + u_i * (1 - exp_lower_2)), -self.lambda_ * np.log(1 - u_i * (1 - exp_upper_2)), ) # beta * span is already exactly zero wherever the span # is, but taking the parent value directly keeps a non-finite beta from reintroducing a NaN. offspring1 = np.where(zero_span, parents1, parents1 + beta_1 * span) offspring2 = np.where(zero_span, parents2, parents2 + beta_2 * span) # The uniform-crossover component, applied before the per-pair crossover probability so that # a pair which does not cross is returned as its parents untouched. # # Each BEX offspring is displaced from *its own* parent, so identity retention is structurally # 1.0: offspring one descends from parent one in every variable. Exchanging the two children's # values for a variable is what gives that variable to the other parent's line, and it is the # same operation `SimulatedBinaryCrossover` performs by flipping the sign of beta -- there the # two children sit symmetrically about the parent midpoint, so a sign flip swaps them exactly. if self.uniform_xover_probability > 0: swap = self.rng.random((mating_pop_size // 2, num_var)) <= self.uniform_xover_probability offspring1, offspring2 = ( np.where(swap, offspring2, offspring1), np.where(swap, offspring1, offspring2), ) mask = self.rng.random(mating_pop_size // 2) > self.xover_probability offspring1[mask, :] = parents1[mask, :] offspring2[mask, :] = parents2[mask, :] children = np.vstack((offspring1, offspring2)) if original_pop_size % 2 == 1: children = children[:-1, :] self.offspring_population = pl.from_numpy(children, schema=self.variable_symbols, orient="row").select( pl.all().cast(pl.Float64) ) self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 1: msgs.append( FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.xover_probability, ) ) msgs.append( FloatMessage( topic=CrossoverMessageTopics.LAMBDA, source=self.__class__.__name__, value=self.lambda_, ) ) if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### CompositeCrossover Bases: `BaseCrossover` Combined crossover operator that combines multiple crossover operators. Source code in `desdeo/emo/operators/crossover.py` ``` class CompositeCrossover(BaseCrossover): """Combined crossover operator that combines multiple crossover operators.""" def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, operators: list[BaseCrossover], seed: int, ): """Initialize the composite crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. operators (list[BaseCrossover]): a list of crossover operators to combine. seed (int): the random seed for reproducibility. Not actually used here. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) self.operators = operators self.turn = 0 def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform crossover using the next operator in the list. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None): indices of individuals to mate. If None, all individuals are considered. Returns: pl.DataFrame: the offspring resulting from the crossover. """ operator = self.operators[self.turn] offspring = operator.do(population=population, to_mate=to_mate) self.turn = (self.turn + 1) % len(self.operators) # No need to notify here, as each operator will handle its own notifications. return offspring @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """This crossover operator does not provide any topics itself.""" return {0: [], 1: [], 2: []} @property def interested_topics(self): """This crossover operator does not have any interested topics itself.""" return [] def update(self, message: Message): """No need to update the composite operator itself. The publisher will handle the updates for each operator.""" return def state(self) -> Sequence[Message]: """This crossover operator does not maintain its own state. For now.""" return [] ``` ##### interested_topics ``` interested_topics ``` This crossover operator does not have any interested topics itself. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` This crossover operator does not provide any topics itself. ##### __init__ ``` __init__( *, problem: Problem, verbosity: int, publisher: Publisher, operators: list[BaseCrossover], seed: int, ) ``` Initialize the composite crossover operator. Parameters: | Name | Type | Description | Default | | ----------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | | `operators` | `list[BaseCrossover]` | a list of crossover operators to combine. | *required* | | `seed` | `int` | the random seed for reproducibility. Not actually used here. | *required* | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, operators: list[BaseCrossover], seed: int, ): """Initialize the composite crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. operators (list[BaseCrossover]): a list of crossover operators to combine. seed (int): the random seed for reproducibility. Not actually used here. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) self.operators = operators self.turn = 0 ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform crossover using the next operator in the list. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | --------------------------------------------- | ------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. | *required* | | `to_mate` | \`list[int] | None\` | indices of individuals to mate. If None, all individuals are considered. | Returns: | Type | Description | | ----------- | --------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform crossover using the next operator in the list. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None): indices of individuals to mate. If None, all individuals are considered. Returns: pl.DataFrame: the offspring resulting from the crossover. """ operator = self.operators[self.turn] offspring = operator.do(population=population, to_mate=to_mate) self.turn = (self.turn + 1) % len(self.operators) # No need to notify here, as each operator will handle its own notifications. return offspring ``` ##### state ``` state() -> Sequence[Message] ``` This crossover operator does not maintain its own state. For now. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """This crossover operator does not maintain its own state. For now.""" return [] ``` ##### update ``` update(message: Message) ``` No need to update the composite operator itself. The publisher will handle the updates for each operator. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, message: Message): """No need to update the composite operator itself. The publisher will handle the updates for each operator.""" return ``` #### DifferentialEvolutionCrossover Bases: `BaseCrossover` Differential evolution recombination, DE/rand/1/bin. For each target vector the operator forms a mutant `v = x_r1 + F * (x_r2 - x_r3)` from three distinct other population members, then mixes `v` with the target componentwise at rate `xover_probability`, forcing at least one component to come from `v` so that no offspring is a copy of its target. With `base_vector="target"` the target itself is the base, `v = x_i + F * (x_r2 - x_r3)`, and only the two donors are drawn. This is the operator of MOEA/D-DE (Li and Zhang 2009, Step 2.2, which sets `r1 = i`), where the target is the current solution of the subproblem being improved. What separates this from the other continuous operators here is *which* individuals set the step size. Every other operator displaces an offspring relative to the parents being recombined, so a solution far from the rest of the population gets a large step and one inside a tight cluster gets a small one. DE's donors are unrelated to the target, so its step is set by the spread of the population at large. Measured on a population of 60 holding one outlier: the outlier's offspring moves 14.3x further than a cluster member's under DE, against 2.1x under SBX. All three of SBX, PCX and DE do contract as the population converges -- SBX's displacement is proportional to the parent difference, so it is not the fixed-versus-adaptive contrast it is sometimes described as. Unlike the other operators in this module, the returned offspring are **target aligned**: row `i` of the output is the child of `to_mate[i]`. The other operators either stack all first children ahead of all second children or interleave them, so lineage is not generically traceable; see the note on `BaseCrossover.do`. References Storn, R., & Price, K. (1997). Differential Evolution - A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces. Journal of Global Optimization, 11(4), 341-359. https://doi.org/10.1023/A:1008202821328 Kukkonen, S., & Lampinen, J. (2005). GDE3: The third evolution step of generalized differential evolution. In 2005 IEEE Congress on Evolutionary Computation (pp. 443-450). https://doi.org/10.1109/CEC.2005.1554717 Li, H., & Zhang, Q. (2009). Multiobjective optimization problems with complicated Pareto sets, MOEA/D and NSGA-II. IEEE Transactions on Evolutionary Computation, 13(2), 284-302. https://doi.org/10.1109/TEVC.2008.925798 (The `base_vector="target"` variant.) Source code in `desdeo/emo/operators/crossover.py` ``` class DifferentialEvolutionCrossover(BaseCrossover): """Differential evolution recombination, DE/rand/1/bin. For each target vector the operator forms a mutant `v = x_r1 + F * (x_r2 - x_r3)` from three distinct other population members, then mixes `v` with the target componentwise at rate `xover_probability`, forcing at least one component to come from `v` so that no offspring is a copy of its target. With `base_vector="target"` the target itself is the base, `v = x_i + F * (x_r2 - x_r3)`, and only the two donors are drawn. This is the operator of MOEA/D-DE (Li and Zhang 2009, Step 2.2, which sets `r1 = i`), where the target is the current solution of the subproblem being improved. What separates this from the other continuous operators here is *which* individuals set the step size. Every other operator displaces an offspring relative to the parents being recombined, so a solution far from the rest of the population gets a large step and one inside a tight cluster gets a small one. DE's donors are unrelated to the target, so its step is set by the spread of the population at large. Measured on a population of 60 holding one outlier: the outlier's offspring moves 14.3x further than a cluster member's under DE, against 2.1x under SBX. All three of SBX, PCX and DE do contract as the population converges -- SBX's displacement is proportional to the parent difference, so it is not the fixed-versus-adaptive contrast it is sometimes described as. Unlike the other operators in this module, the returned offspring are **target aligned**: row `i` of the output is the child of `to_mate[i]`. The other operators either stack all first children ahead of all second children or interleave them, so lineage is not generically traceable; see the note on `BaseCrossover.do`. References: Storn, R., & Price, K. (1997). Differential Evolution - A Simple and Efficient Heuristic for Global Optimization over Continuous Spaces. Journal of Global Optimization, 11(4), 341-359. https://doi.org/10.1023/A:1008202821328 Kukkonen, S., & Lampinen, J. (2005). GDE3: The third evolution step of generalized differential evolution. In 2005 IEEE Congress on Evolutionary Computation (pp. 443-450). https://doi.org/10.1109/CEC.2005.1554717 Li, H., & Zhang, Q. (2009). Multiobjective optimization problems with complicated Pareto sets, MOEA/D and NSGA-II. IEEE Transactions on Evolutionary Computation, 13(2), 284-302. https://doi.org/10.1109/TEVC.2008.925798 (The `base_vector="target"` variant.) """ _MIN_POPULATION = 4 """A target plus three distinct donors.""" @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the differential evolution crossover operator.""" return { 0: [], 1: [ CrossoverMessageTopics.XOVER_PROBABILITY, CrossoverMessageTopics.SCALING_FACTOR, ], 2: [ CrossoverMessageTopics.XOVER_PROBABILITY, CrossoverMessageTopics.SCALING_FACTOR, CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The differential evolution crossover operator listens to nothing.""" return [] def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, scaling_factor: float = 0.5, xover_probability: float = 0.9, base_vector: Literal["random", "target"] = "random", ): """Initialize the differential evolution crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): the seed used in the random number generator. scaling_factor (float, optional): the factor `F` applied to the difference vector. Defaults to 0.5, the midpoint of the 0.4-1.0 range Storn and Price recommend. xover_probability (float, optional): the binomial crossover rate `CR`, the per-component probability that the offspring takes the mutant's value rather than the target's. Defaults to 0.9. base_vector (Literal["random", "target"], optional): the vector the scaled difference is added to. "random" draws it as a third donor (DE/rand/1); "target" uses the target itself, as MOEA/D-DE does. Defaults to "random". """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("DifferentialEvolutionCrossover only works on continuous problems.") if scaling_factor <= 0: raise ValueError("scaling_factor must be positive.") if not 0 <= xover_probability <= 1: raise ValueError("xover_probability must be in [0,1].") if base_vector not in ("random", "target"): raise ValueError("base_vector must be 'random' or 'target'.") self.scaling_factor = scaling_factor self.xover_probability = xover_probability self.base_vector = base_vector def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform DE/rand/1/bin crossover, producing one offspring per target. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover, one row per target. """ whole = population[self.variable_symbols].to_numpy() pop_size = whole.shape[0] if pop_size < self._MIN_POPULATION: raise ValueError( f"DifferentialEvolutionCrossover needs at least {self._MIN_POPULATION} individuals, " f"a target and three distinct donors, but the population holds {pop_size}." ) # `get_parents` is not used: it pads an odd mating pool with a duplicate so that pairs come # out even, and DE has no pairs. The donors are drawn from the whole population, which is # what DE/rand/1 specifies, so `to_mate` selects targets only. targets = np.arange(pop_size) if to_mate is None else np.asarray(to_mate, dtype=np.int64) num_offspring, num_var = targets.shape[0], whole.shape[1] self.parent_population = population[targets.tolist()] if self.base_vector == "target": donors = _distinct_indices(self.rng, targets, pop_size, k=2) mutant = whole[targets] + self.scaling_factor * (whole[donors[:, 0]] - whole[donors[:, 1]]) else: donors = _distinct_indices(self.rng, targets, pop_size, k=3) mutant = whole[donors[:, 0]] + self.scaling_factor * (whole[donors[:, 1]] - whole[donors[:, 2]]) take_mutant = self.rng.random((num_offspring, num_var)) < self.xover_probability # One component is always inherited from the mutant, so an offspring is never a copy of its # target even at xover_probability = 0. This is the `jrand` of the original formulation. forced = self.rng.integers(0, num_var, size=num_offspring) take_mutant[np.arange(num_offspring), forced] = True offsprings = np.where(take_mutant, mutant, whole[targets]) offsprings = np.clip(offsprings, np.asarray(self.lower_bounds), np.asarray(self.upper_bounds)) self.offspring_population = pl.from_numpy(offsprings, schema=self.variable_symbols, orient="row") self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the differential evolution crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 1: msgs.extend( [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.xover_probability, ), FloatMessage( topic=CrossoverMessageTopics.SCALING_FACTOR, source=self.__class__.__name__, value=self.scaling_factor, ), ] ) if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### \_MIN_POPULATION ``` _MIN_POPULATION = 4 ``` A target plus three distinct donors. ##### interested_topics ``` interested_topics ``` The differential evolution crossover operator listens to nothing. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the differential evolution crossover operator. ##### __init__ ``` __init__( *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, scaling_factor: float = 0.5, xover_probability: float = 0.9, base_vector: Literal["random", "target"] = "random", ) ``` Initialize the differential evolution crossover operator. Parameters: | Name | Type | Description | Default | | ------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | | `seed` | `int` | the seed used in the random number generator. | *required* | | `scaling_factor` | `float` | the factor F applied to the difference vector. Defaults to 0.5, the midpoint of the 0.4-1.0 range Storn and Price recommend. | `0.5` | | `xover_probability` | `float` | the binomial crossover rate CR, the per-component probability that the offspring takes the mutant's value rather than the target's. Defaults to 0.9. | `0.9` | | `base_vector` | `Literal['random', 'target']` | the vector the scaled difference is added to. "random" draws it as a third donor (DE/rand/1); "target" uses the target itself, as MOEA/D-DE does. Defaults to "random". | `'random'` | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, scaling_factor: float = 0.5, xover_probability: float = 0.9, base_vector: Literal["random", "target"] = "random", ): """Initialize the differential evolution crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): the seed used in the random number generator. scaling_factor (float, optional): the factor `F` applied to the difference vector. Defaults to 0.5, the midpoint of the 0.4-1.0 range Storn and Price recommend. xover_probability (float, optional): the binomial crossover rate `CR`, the per-component probability that the offspring takes the mutant's value rather than the target's. Defaults to 0.9. base_vector (Literal["random", "target"], optional): the vector the scaled difference is added to. "random" draws it as a third donor (DE/rand/1); "target" uses the target itself, as MOEA/D-DE does. Defaults to "random". """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("DifferentialEvolutionCrossover only works on continuous problems.") if scaling_factor <= 0: raise ValueError("scaling_factor must be positive.") if not 0 <= xover_probability <= 1: raise ValueError("xover_probability must be in [0,1].") if base_vector not in ("random", "target"): raise ValueError("base_vector must be 'random' or 'target'.") self.scaling_factor = scaling_factor self.xover_probability = xover_probability self.base_vector = base_vector ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform DE/rand/1/bin crossover, producing one offspring per target. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | ----------------------------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover, one row per target. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform DE/rand/1/bin crossover, producing one offspring per target. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover, one row per target. """ whole = population[self.variable_symbols].to_numpy() pop_size = whole.shape[0] if pop_size < self._MIN_POPULATION: raise ValueError( f"DifferentialEvolutionCrossover needs at least {self._MIN_POPULATION} individuals, " f"a target and three distinct donors, but the population holds {pop_size}." ) # `get_parents` is not used: it pads an odd mating pool with a duplicate so that pairs come # out even, and DE has no pairs. The donors are drawn from the whole population, which is # what DE/rand/1 specifies, so `to_mate` selects targets only. targets = np.arange(pop_size) if to_mate is None else np.asarray(to_mate, dtype=np.int64) num_offspring, num_var = targets.shape[0], whole.shape[1] self.parent_population = population[targets.tolist()] if self.base_vector == "target": donors = _distinct_indices(self.rng, targets, pop_size, k=2) mutant = whole[targets] + self.scaling_factor * (whole[donors[:, 0]] - whole[donors[:, 1]]) else: donors = _distinct_indices(self.rng, targets, pop_size, k=3) mutant = whole[donors[:, 0]] + self.scaling_factor * (whole[donors[:, 1]] - whole[donors[:, 2]]) take_mutant = self.rng.random((num_offspring, num_var)) < self.xover_probability # One component is always inherited from the mutant, so an offspring is never a copy of its # target even at xover_probability = 0. This is the `jrand` of the original formulation. forced = self.rng.integers(0, num_var, size=num_offspring) take_mutant[np.arange(num_offspring), forced] = True offsprings = np.where(take_mutant, mutant, whole[targets]) offsprings = np.clip(offsprings, np.asarray(self.lower_bounds), np.asarray(self.upper_bounds)) self.offspring_population = pl.from_numpy(offsprings, schema=self.variable_symbols, orient="row") self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the differential evolution crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the differential evolution crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 1: msgs.extend( [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.xover_probability, ), FloatMessage( topic=CrossoverMessageTopics.SCALING_FACTOR, source=self.__class__.__name__, value=self.scaling_factor, ), ] ) if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### LocalCrossover Bases: `BaseCrossover` Local Crossover for continuous problems. An arithmetic crossover that draws a fresh blending weight for every decision variable of every mating pair, rather than one weight for the whole vector. The two offspring use complementary weights, so each pair spans the segment between the parents component by component. References Dumitrescu, D., Lazzerini, B., Jain, L. C., & Dumitrescu, A. (2000). Evolutionary Computation. CRC Press, Florida, USA. Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 Source code in `desdeo/emo/operators/crossover.py` ``` class LocalCrossover(BaseCrossover): """Local Crossover for continuous problems. An arithmetic crossover that draws a fresh blending weight for every decision variable of every mating pair, rather than one weight for the whole vector. The two offspring use complementary weights, so each pair spans the segment between the parents component by component. References: Dumitrescu, D., Lazzerini, B., Jain, L. C., & Dumitrescu, A. (2000). Evolutionary Computation. CRC Press, Florida, USA. Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 """ @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the local crossover operator. Note: The operator has no crossover probability, so it does not provide that topic. """ return { 0: [], 1: [], 2: [ CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics that the local crossover operator is interested in.""" return [] def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, seed: int, ): """Initialize the local crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): random seed for reproducibility. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("LocalCrossover only works on continuous problems.") def do(self, *, population: pl.DataFrame, to_mate: list[int] | None = None) -> pl.DataFrame: """Perform Local Crossover. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy() mating_pop_size = mating_pop.shape[0] num_var = mating_pop.shape[1] original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] parents1 = mating_pop[0::2] parents2 = mating_pop[1::2] offspring = np.empty((mating_pop_size, num_var)) for i in range(mating_pop_size // 2): alpha = self.rng.random(num_var) offspring[2 * i] = alpha * parents1[i] + (1 - alpha) * parents2[i] offspring[2 * i + 1] = (1 - alpha) * parents1[i] + alpha * parents2[i] # An odd sized mating pool was padded with a duplicate parent, so the last pair produced one # offspring too many. Drop it, as every other crossover operator here does. if original_pop_size % 2 == 1: offspring = offspring[:-1, :] self.offspring_population = pl.from_numpy(offspring, schema=self.variable_symbols, orient="row").select( pl.all().cast(pl.Float64) ) self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the local crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### interested_topics ``` interested_topics ``` The message topics that the local crossover operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the local crossover operator. Note The operator has no crossover probability, so it does not provide that topic. ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, seed: int, ) ``` Initialize the local crossover operator. Parameters: | Name | Type | Description | Default | | ----------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | | `seed` | `int` | random seed for reproducibility. | *required* | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, seed: int, ): """Initialize the local crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): random seed for reproducibility. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("LocalCrossover only works on continuous problems.") ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform Local Crossover. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | --------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do(self, *, population: pl.DataFrame, to_mate: list[int] | None = None) -> pl.DataFrame: """Perform Local Crossover. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy() mating_pop_size = mating_pop.shape[0] num_var = mating_pop.shape[1] original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] parents1 = mating_pop[0::2] parents2 = mating_pop[1::2] offspring = np.empty((mating_pop_size, num_var)) for i in range(mating_pop_size // 2): alpha = self.rng.random(num_var) offspring[2 * i] = alpha * parents1[i] + (1 - alpha) * parents2[i] offspring[2 * i + 1] = (1 - alpha) * parents1[i] + alpha * parents2[i] # An odd sized mating pool was padded with a duplicate parent, so the last pair produced one # offspring too many. Drop it, as every other crossover operator here does. if original_pop_size % 2 == 1: offspring = offspring[:-1, :] self.offspring_population = pl.from_numpy(offspring, schema=self.variable_symbols, orient="row").select( pl.all().cast(pl.Float64) ) self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the local crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the local crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### ParentCentricCrossover Bases: `BaseCrossover` Parent-centric crossover (PCX) for continuous problems. Three parents are drawn per offspring. One of them is the *index* parent, and the offspring is placed near it: displaced along the direction from the parental centroid to the index parent by a normal draw of standard deviation `sigma_zeta`, and orthogonally to that direction by a normal draw of standard deviation `sigma_eta`, scaled by how far the other two parents sit from that direction. The population's own geometry therefore sets the step size in both directions. The contrast with SBX, the other parent-centric operator here, is structural rather than a matter of scale. SBX perturbs each decision variable independently along its own axis and has no notion of a direction in decision space. PCX's displacement decomposes into a component along the centroid-to-parent direction and an isotropic component orthogonal to it, so the parental geometry decides where the offspring goes and not merely how far. With `sigma_eta` at zero the orthogonal part vanishes and every offspring lies exactly on the centroid-to-parent ray, which is what `test_parent_centric_crossover_displaces_along_the_centroid_direction` checks. Note Deb, Anand and Joshi write the orthogonal part as a sum over an orthonormal basis of the complement of the parent-to-centroid direction, with an independent normal coefficient on each basis vector. Building that basis costs a Gram-Schmidt pass per offspring. This implementation instead draws an isotropic normal vector in the full space and projects the parent-to-centroid component out of it, which has exactly the same distribution -- an isotropic Gaussian projected onto a subspace is an isotropic Gaussian on that subspace -- and costs one dot product. References Deb, K., Anand, A., & Joshi, D. (2002). A computationally efficient evolutionary algorithm for real-parameter optimization. Evolutionary Computation, 10(4), 371-395. https://doi.org/10.1162/106365602760972767 Source code in `desdeo/emo/operators/crossover.py` ``` class ParentCentricCrossover(BaseCrossover): """Parent-centric crossover (PCX) for continuous problems. Three parents are drawn per offspring. One of them is the *index* parent, and the offspring is placed near it: displaced along the direction from the parental centroid to the index parent by a normal draw of standard deviation `sigma_zeta`, and orthogonally to that direction by a normal draw of standard deviation `sigma_eta`, scaled by how far the other two parents sit from that direction. The population's own geometry therefore sets the step size in both directions. The contrast with SBX, the other parent-centric operator here, is structural rather than a matter of scale. SBX perturbs each decision variable independently along its own axis and has no notion of a direction in decision space. PCX's displacement decomposes into a component along the centroid-to-parent direction and an isotropic component orthogonal to it, so the parental geometry decides where the offspring goes and not merely how far. With `sigma_eta` at zero the orthogonal part vanishes and every offspring lies exactly on the centroid-to-parent ray, which is what `test_parent_centric_crossover_displaces_along_the_centroid_direction` checks. Note: Deb, Anand and Joshi write the orthogonal part as a sum over an orthonormal basis of the complement of the parent-to-centroid direction, with an independent normal coefficient on each basis vector. Building that basis costs a Gram-Schmidt pass per offspring. This implementation instead draws an isotropic normal vector in the full space and projects the parent-to-centroid component out of it, which has exactly the same distribution -- an isotropic Gaussian projected onto a subspace is an isotropic Gaussian on that subspace -- and costs one dot product. References: Deb, K., Anand, A., & Joshi, D. (2002). A computationally efficient evolutionary algorithm for real-parameter optimization. Evolutionary Computation, 10(4), 371-395. https://doi.org/10.1162/106365602760972767 """ _MIN_POPULATION = 3 """An index parent and two others to set the orthogonal scale.""" _DEGENERATE = 1e-12 """Below this, the index parent sits on the centroid and the direction is undefined.""" @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the parent-centric crossover operator. Note: The operator recombines every selected parent, so it has no crossover probability and does not provide that topic. """ return { 0: [], 1: [ CrossoverMessageTopics.SIGMA_ZETA, CrossoverMessageTopics.SIGMA_ETA, ], 2: [ CrossoverMessageTopics.SIGMA_ZETA, CrossoverMessageTopics.SIGMA_ETA, CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The parent-centric crossover operator listens to nothing.""" return [] def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, sigma_zeta: float = 0.1, sigma_eta: float = 0.1, ): """Initialize the parent-centric crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): the seed used in the random number generator. sigma_zeta (float, optional): standard deviation of the displacement along the centroid-to-index-parent direction. Defaults to 0.1, the value used throughout Deb, Anand and Joshi (2002). sigma_eta (float, optional): standard deviation of the displacement orthogonal to that direction, in units of the mean perpendicular distance of the other parents. Defaults to 0.1. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("ParentCentricCrossover only works on continuous problems.") if sigma_zeta <= 0: raise ValueError("sigma_zeta must be positive.") if sigma_eta <= 0: raise ValueError("sigma_eta must be positive.") self.sigma_zeta = sigma_zeta self.sigma_eta = sigma_eta def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform PCX, producing one offspring per index parent. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover, one row per index parent. """ whole = population[self.variable_symbols].to_numpy() pop_size = whole.shape[0] if pop_size < self._MIN_POPULATION: raise ValueError( f"ParentCentricCrossover needs at least {self._MIN_POPULATION} individuals, but the " f"population holds {pop_size}." ) # As in DE, `get_parents` is not used: PCX draws a triple rather than a pair, so padding the # pool to an even length would serve no purpose. `to_mate` selects the index parents. index_parents = np.arange(pop_size) if to_mate is None else np.asarray(to_mate, dtype=np.int64) num_offspring, num_var = index_parents.shape[0], whole.shape[1] self.parent_population = population[index_parents.tolist()] others = _distinct_indices(self.rng, index_parents, pop_size, k=2) index_x = whole[index_parents] other_a, other_b = whole[others[:, 0]], whole[others[:, 1]] centroid = (index_x + other_a + other_b) / 3.0 direction = index_x - centroid norm = np.linalg.norm(direction, axis=1, keepdims=True) # An index parent sitting on the centroid means all three parents coincide. The direction is # then undefined; fall back to an unprojected isotropic step, which is the limit of the # operator as the triangle collapses. degenerate = norm[:, 0] < self._DEGENERATE unit = np.divide(direction, np.where(norm < self._DEGENERATE, 1.0, norm)) # Mean perpendicular distance of the other two parents from the line through the index parent. perpendicular = [] for other in (other_a, other_b): offset = other - index_x along = np.sum(offset * unit, axis=1, keepdims=True) * unit perpendicular.append(np.linalg.norm(offset - along, axis=1)) spread = np.mean(perpendicular, axis=0)[:, None] orthogonal = self.rng.normal(0.0, self.sigma_eta, size=(num_offspring, num_var)) projection = np.sum(orthogonal * unit, axis=1, keepdims=True) * unit orthogonal = np.where(degenerate[:, None], orthogonal, orthogonal - projection) along_direction = self.rng.normal(0.0, self.sigma_zeta, size=(num_offspring, 1)) offsprings = index_x + along_direction * direction + spread * orthogonal offsprings = np.clip(offsprings, np.asarray(self.lower_bounds), np.asarray(self.upper_bounds)) self.offspring_population = pl.from_numpy(offsprings, schema=self.variable_symbols, orient="row") self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the parent-centric crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 1: msgs.extend( [ FloatMessage( topic=CrossoverMessageTopics.SIGMA_ZETA, source=self.__class__.__name__, value=self.sigma_zeta, ), FloatMessage( topic=CrossoverMessageTopics.SIGMA_ETA, source=self.__class__.__name__, value=self.sigma_eta, ), ] ) if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### \_DEGENERATE ``` _DEGENERATE = 1e-12 ``` Below this, the index parent sits on the centroid and the direction is undefined. ##### \_MIN_POPULATION ``` _MIN_POPULATION = 3 ``` An index parent and two others to set the orthogonal scale. ##### interested_topics ``` interested_topics ``` The parent-centric crossover operator listens to nothing. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the parent-centric crossover operator. Note The operator recombines every selected parent, so it has no crossover probability and does not provide that topic. ##### __init__ ``` __init__( *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, sigma_zeta: float = 0.1, sigma_eta: float = 0.1, ) ``` Initialize the parent-centric crossover operator. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | | `seed` | `int` | the seed used in the random number generator. | *required* | | `sigma_zeta` | `float` | standard deviation of the displacement along the centroid-to-index-parent direction. Defaults to 0.1, the value used throughout Deb, Anand and Joshi (2002). | `0.1` | | `sigma_eta` | `float` | standard deviation of the displacement orthogonal to that direction, in units of the mean perpendicular distance of the other parents. Defaults to 0.1. | `0.1` | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__( self, *, problem: Problem, verbosity: int, publisher: Publisher, seed: int, sigma_zeta: float = 0.1, sigma_eta: float = 0.1, ): """Initialize the parent-centric crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. publisher (Publisher): the publisher to which the operator will publish messages. seed (int): the seed used in the random number generator. sigma_zeta (float, optional): standard deviation of the displacement along the centroid-to-index-parent direction. Defaults to 0.1, the value used throughout Deb, Anand and Joshi (2002). sigma_eta (float, optional): standard deviation of the displacement orthogonal to that direction, in units of the mean perpendicular distance of the other parents. Defaults to 0.1. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("ParentCentricCrossover only works on continuous problems.") if sigma_zeta <= 0: raise ValueError("sigma_zeta must be positive.") if sigma_eta <= 0: raise ValueError("sigma_eta must be positive.") self.sigma_zeta = sigma_zeta self.sigma_eta = sigma_eta ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform PCX, producing one offspring per index parent. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | ----------------------------------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover, one row per index parent. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform PCX, producing one offspring per index parent. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover, one row per index parent. """ whole = population[self.variable_symbols].to_numpy() pop_size = whole.shape[0] if pop_size < self._MIN_POPULATION: raise ValueError( f"ParentCentricCrossover needs at least {self._MIN_POPULATION} individuals, but the " f"population holds {pop_size}." ) # As in DE, `get_parents` is not used: PCX draws a triple rather than a pair, so padding the # pool to an even length would serve no purpose. `to_mate` selects the index parents. index_parents = np.arange(pop_size) if to_mate is None else np.asarray(to_mate, dtype=np.int64) num_offspring, num_var = index_parents.shape[0], whole.shape[1] self.parent_population = population[index_parents.tolist()] others = _distinct_indices(self.rng, index_parents, pop_size, k=2) index_x = whole[index_parents] other_a, other_b = whole[others[:, 0]], whole[others[:, 1]] centroid = (index_x + other_a + other_b) / 3.0 direction = index_x - centroid norm = np.linalg.norm(direction, axis=1, keepdims=True) # An index parent sitting on the centroid means all three parents coincide. The direction is # then undefined; fall back to an unprojected isotropic step, which is the limit of the # operator as the triangle collapses. degenerate = norm[:, 0] < self._DEGENERATE unit = np.divide(direction, np.where(norm < self._DEGENERATE, 1.0, norm)) # Mean perpendicular distance of the other two parents from the line through the index parent. perpendicular = [] for other in (other_a, other_b): offset = other - index_x along = np.sum(offset * unit, axis=1, keepdims=True) * unit perpendicular.append(np.linalg.norm(offset - along, axis=1)) spread = np.mean(perpendicular, axis=0)[:, None] orthogonal = self.rng.normal(0.0, self.sigma_eta, size=(num_offspring, num_var)) projection = np.sum(orthogonal * unit, axis=1, keepdims=True) * unit orthogonal = np.where(degenerate[:, None], orthogonal, orthogonal - projection) along_direction = self.rng.normal(0.0, self.sigma_zeta, size=(num_offspring, 1)) offsprings = index_x + along_direction * direction + spread * orthogonal offsprings = np.clip(offsprings, np.asarray(self.lower_bounds), np.asarray(self.upper_bounds)) self.offspring_population = pl.from_numpy(offsprings, schema=self.variable_symbols, orient="row") self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the parent-centric crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the parent-centric crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] if self.verbosity >= 1: msgs.extend( [ FloatMessage( topic=CrossoverMessageTopics.SIGMA_ZETA, source=self.__class__.__name__, value=self.sigma_zeta, ), FloatMessage( topic=CrossoverMessageTopics.SIGMA_ETA, source=self.__class__.__name__, value=self.sigma_eta, ), ] ) if self.verbosity >= 2: # noqa: PLR2004 msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### SimulatedBinaryCrossover Bases: `BaseCrossover` A class for creating a simulated binary crossover operator. Both the original untruncated operator and the truncated variant that keeps the offspring inside the variable bounds are available; see `unbounded_offsprings` and `bounded_offsprings`. The truncated variant is the default, as in pymoo, jMetalPy, Platypus, pagmo2 and Deb's own NSGA-II code; pass `truncated=False` for the untruncated formulation that PlatEMO implements. References Deb, K., & Agrawal, R. B. (1995). Simulated binary crossover for continuous search space. Complex Systems, 9(2), 115-148. Deb, K., & Gulati, S. (2001). Design of truss-structures for minimum weight using genetic algorithms. Finite Elements in Analysis and Design, 37(5), 447-465. https://doi.org/10.1016/S0168-874X(00)00057-3 (The truncated variant, which is the default.) Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 (Empirical comparison against other real-coded recombination operators.) Source code in `desdeo/emo/operators/crossover.py` ``` class SimulatedBinaryCrossover(BaseCrossover): """A class for creating a simulated binary crossover operator. Both the original untruncated operator and the truncated variant that keeps the offspring inside the variable bounds are available; see `unbounded_offsprings` and `bounded_offsprings`. The truncated variant is the default, as in pymoo, jMetalPy, Platypus, pagmo2 and Deb's own NSGA-II code; pass `truncated=False` for the untruncated formulation that PlatEMO implements. References: Deb, K., & Agrawal, R. B. (1995). Simulated binary crossover for continuous search space. Complex Systems, 9(2), 115-148. Deb, K., & Gulati, S. (2001). Design of truss-structures for minimum weight using genetic algorithms. Finite Elements in Analysis and Design, 37(5), 447-465. https://doi.org/10.1016/S0168-874X(00)00057-3 (The truncated variant, which is the default.) Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 (Empirical comparison against other real-coded recombination operators.) """ @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the crossover operator.""" return { 0: [], 1: [CrossoverMessageTopics.XOVER_PROBABILITY, CrossoverMessageTopics.XOVER_DISTRIBUTION], 2: [ CrossoverMessageTopics.XOVER_PROBABILITY, CrossoverMessageTopics.XOVER_DISTRIBUTION, CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics the crossover operator is interested in.""" return [] def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, pair_xover_probability: float = 1.0, xover_probability: float = 0.5, uniform_xover_probability: float = 0.5, xover_distribution: float = 30, truncated: bool = True, swap_uncrossed_variables: bool = False, ): """Initialize a simulated binary crossover operator. Args: problem (Problem): the problem object. seed (int): the seed for the random number generator. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. pair_xover_probability (float, optional): the probability that a parent pair is recombined at all. Drawn once per pair: on failure the pair is copied to the offspring unchanged, with every decision variable kept together. This is the `p_c` reported in the literature (1.0 in the RVEA and NSGA-III papers, 0.9 in NSGA-II). Ranges between 0 and 1.0. Defaults to 1.0. xover_probability (float, optional): the per-variable crossover probability. Drawn once per decision variable, and decides whether the SBX operation is performed on that variable. Ranges between 0 and 1.0. Defaults to 0.5, following Deb and Agrawal (1995), who state "we choose to perform SBX in each variable with probability 0.5". Note this is a *separate* level from `pair_xover_probability`: the literature's `p_c = 1.0` refers to the pair, not to the variable, so it belongs in `pair_xover_probability`. uniform_xover_probability (float, optional): the uniform crossover probability parameter. This parameter decides whether the decision variable components of the parents are swapped for the offspring or not. Ranges between 0 and 1.0. Defaults to 0.5. Only operates on variables that have already been selected for crossover by the xover_probability parameter. xover_distribution (float, optional): the crossover distribution parameter. Must be positive. This parameter controls the distribution of the offspring. A larger value results in a distribution that is more concentrated around the parents, while a smaller value results in a distribution that is more spread out. Defaults to 30. truncated (bool, optional): whether to truncate the probability distribution to keep the offspring within the variable bounds. Defaults to True. swap_uncrossed_variables (bool, optional): whether a decision variable *not* selected by `xover_probability` is exchanged between the two offspring instead of inherited unchanged. Defaults to False, which is what every implementation surveyed does except jMetal (Java). jMetal's else-branch assigns `offspring1[i] = parent2[i]` and `offspring2[i] = parent1[i]`, adding a genuine uniform-crossover component on top of SBX: at the standard per-variable rate of 0.5, half of the genome is swapped wholesale every time a pair recombines. Set it to reproduce jMetal; leave it alone otherwise. """ # Subscribes to no topics, so no need to stroe/pass the topics to the super class. super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) self.problem = problem if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("SimulatedBinaryCrossover only works on continuous problems.") if not 0 <= pair_xover_probability <= 1: raise ValueError("Pair crossover probability must be between 0 and 1.") if not 0 <= xover_probability <= 1: raise ValueError("Crossover probability must be between 0 and 1.") if xover_distribution <= 0: raise ValueError("Crossover distribution must be positive.") self.pair_xover_probability = pair_xover_probability self.xover_probability = xover_probability self.xover_distribution = xover_distribution self.uniform_xover_probability = uniform_xover_probability self.truncated = truncated self.swap_uncrossed_variables = swap_uncrossed_variables def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform the simulated binary crossover operation. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ if self.truncated: offspring = self.bounded_offsprings(population=population, to_mate=to_mate) else: offspring = self.unbounded_offsprings(population=population, to_mate=to_mate) # An odd sized mating pool was padded with a duplicate parent, so the last pair produced one # offspring too many. original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] if original_pop_size % 2 == 1: offspring = offspring.head(original_pop_size) self.offspring_population = offspring self.notify() return self.offspring_population def unbounded_offsprings( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform the unbounded simulated binary crossover operation. Implementation based on Deb, Kalyanmoy, and Ram Bhushan Agrawal. "Simulated binary crossover for continuous search space." Complex systems 9.2 (1995): 115-148. This implementation follows PlatEMO's `OperatorGA`. DEAP's `cxSimulatedBinary` derives the same beta, but omits the random sign and the per-variable mask that PlatEMO adds on top of the paper. pymoo, DEAP's `cxSimulatedBinaryBounded`, jMetalPy, Platypus, pagmo2 and Deb's own NSGA-II C code all implement the truncated/bounded variant while calling it simulated binary crossover; see `bounded_offsprings` for that one. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy().astype(float) mate_size = mating_pop.shape[0] num_var = mating_pop.shape[1] offspring = np.zeros_like(mating_pop) HALF = 0.5 # NOQA: N806 # TODO(@light-weaver): Extract into a numba jitted function. for i in range(0, mate_size, 2): # One draw per pair, before any per-variable draw. A pair that fails is copied whole, so # all of its variables stay together -- that within-pair correlation is the point, and is # what folding p_c into the per-variable rate would destroy. if self.rng.random() > self.pair_xover_probability: offspring[i] = mating_pop[i] offspring[i + 1] = mating_pop[i + 1] continue beta = np.zeros(num_var) miu = self.rng.random(num_var) # Simulated binary crossover (SBX) operator tries to mimic the behavior of single-point crossover by # trying to attain similar distribution of offspring as single-point crossover. # The distribution itself can be contracting or expanding. # beta is calculated such that the integral (over (0, beta)) of the distribution matches the random number # mu. At mu <= 0.5, the distribution is contracting, and at mu > 0.5, the distribution is expanding. # You can integrate equations 18 and 19 from the reference in the docstring to see how the equations below # are derived. Integrate 18 from 0 to beta, and set it equal to mu. Solve for beta. # for 19, first integrate 18 from 0 to 1 (which is equal to 0.5 so you don't actually need to integrate it) # Then add the integral of 19 from 1 to beta, and set it equal to mu. Solve for beta. beta[miu <= HALF] = (2 * miu[miu <= HALF]) ** (1 / (self.xover_distribution + 1)) # 18 beta[miu > HALF] = (2 - 2 * miu[miu > HALF]) ** (-1 / (self.xover_distribution + 1)) # 18 + 19 # if beta is negative, the offspring 1 gets decision var component closer to parent 2 and vice versa. # In this implementation, there is an equal chance of beta being negative or positive. # TBH, this is more similar to uniform crossover than single-point crossover. binary_mask = self.rng.random(num_var) <= self.uniform_xover_probability binary_mask = (binary_mask * 2) - 1 # Convert to -1 or 1 beta = beta * binary_mask # At beta = -1 no crossover occurs and the dec var components are copied from the parents: # offspring[i] = avg + diff = mating_pop[i]. (Beta = +1 would swap the parents instead, # which is what PlatEMO's opposite sign convention on the offspring expression means by # setting the sentinel to +1 there.) # jMetal wants exactly that swap on the uncrossed variables, so the sentinel flips sign. uncrossed_sentinel = 1 if self.swap_uncrossed_variables else -1 beta[self.rng.random(num_var) > self.xover_probability] = uncrossed_sentinel # Note that when mu < 0.5, abs(beta) ends up being less than 1, resulting in a contracting crossover. # The opposite is true when mu > 0.5, resulting in an expanding crossover. avg = (mating_pop[i] + mating_pop[i + 1]) / 2 diff = (mating_pop[i] - mating_pop[i + 1]) / 2 offspring[i] = avg - beta * diff offspring[i + 1] = avg + beta * diff # Clip the offspring to the bounds lower_bounds = np.asarray(self.lower_bounds, dtype=float) upper_bounds = np.asarray(self.upper_bounds, dtype=float) offspring = np.clip(offspring, lower_bounds, upper_bounds) return pl.from_numpy(offspring, schema=self.variable_symbols, orient="row") def bounded_offsprings( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform the bounded simulated binary crossover operation. This implementation is similar to pymoo and boundedSBX in deap. One of the first papers I can find that actually describes how to calculate it is [1]. The basic idea is as follows: 1. Take the probability distributions of the unbounded SBX operator. There are two: one for the contracting case (mu <= 0.5, beta <= 1) and one for the expanding case (mu > 0.5, beta > 1). 2. Assume that we are bounded on the lower side. Calculate a maximum value of beta such that any potential offspring will not be below the lower bound. This is done by solving for beta in the equation: c = (p1+p2)/2 - beta*(p1-p2)/2, where c is the child (or in this case, the lower bound), p1 and p2 are parents. Thus, beta_max = (p1+p2-2*c)/(p1-p2). This is the maximum value of beta such that the child will still be above the lower bound. In most implementations, this is called beta_q, and the equation is slightly rearranged to be beta_q = 1 + 2*(p1-x_L)/(p2-p1), where p1 self.pair_xover_probability: offspring[i] = mating_pop[i] offspring[i + 1] = mating_pop[i + 1] continue beta = np.zeros(num_var) miu = self.rng.random(num_var) # Apply crossover only for certain decision variables sbx_mask = self.rng.random(num_var) <= self.xover_probability # Apply binary crossover only for certain decision variables binary_mask = self.rng.random(num_var) <= self.uniform_xover_probability binary_mask = binary_mask & sbx_mask # Only apply binary crossover where SBX is applied avg = (mating_pop[i] + mating_pop[i + 1]) / 2 x1 = np.minimum(mating_pop[i], mating_pop[i + 1]) x2 = np.maximum(mating_pop[i], mating_pop[i + 1]) # The two children are derived in *sorted* order: one steps from the midpoint down towards # the lower bound, the other up towards the upper bound, and each uses the beta capped by # the distance to the bound it is stepping towards. The half-difference must therefore be # taken between the sorted values, not between the parents in whatever order the mating # pool happens to hold them. Using the unsorted difference pairs the lower-bound beta with # an upward step (and vice versa) whenever mating_pop[i] is the smaller parent, which lets # the offspring escape the variable bounds. diff = (x2 - x1) / 2 # Child stepping towards the lower bound. with np.errstate(divide="ignore", invalid="ignore"): # Handles x1 == x2 case beta_max = 1 + 2 * (x1 - lower_bounds) / (x2 - x1) beta_max[np.isnan(beta_max)] = np.inf # Handles x1 == x2 == lower_bound case # Technically, this code can handle the unbounded case by setting alpha to an array of 2s. alpha = 2 - (1 / beta_max) ** (self.xover_distribution + 1) SPLIT_POINT1 = 1 / alpha # NOQA: N806 beta[miu <= SPLIT_POINT1] = (alpha[miu <= SPLIT_POINT1] * miu[miu <= SPLIT_POINT1]) ** ( 1 / (self.xover_distribution + 1) ) beta[miu > SPLIT_POINT1] = (2 - alpha[miu > SPLIT_POINT1] * miu[miu > SPLIT_POINT1]) ** ( -1 / (self.xover_distribution + 1) ) # Turning beta negative does not work for truncated SBX. Manually swap the offspring instead. child_low = avg - beta * diff # Child stepping towards the upper bound. The same miu is reused deliberately: every # reference implementation draws one uniform per variable and shares it between the two # children, so that the pair is perfectly correlated. with np.errstate(divide="ignore", invalid="ignore"): # Handles x1 == x2 case beta_max = 1 + 2 * (upper_bounds - x2) / (x2 - x1) beta_max[np.isnan(beta_max)] = np.inf # Handles x1 == x2 == upper_bound case # The error states only occur when x1==x2, which means that the parents are equal, and thus the offspring # will be equal to the parents. So, np.inf is fine. alpha = 2 - (1 / beta_max) ** (self.xover_distribution + 1) SPLIT_POINT2 = 1 / alpha # NOQA: N806 beta[miu <= SPLIT_POINT2] = (alpha[miu <= SPLIT_POINT2] * miu[miu <= SPLIT_POINT2]) ** ( 1 / (self.xover_distribution + 1) ) beta[miu > SPLIT_POINT2] = (2 - alpha[miu > SPLIT_POINT2] * miu[miu > SPLIT_POINT2]) ** ( -1 / (self.xover_distribution + 1) ) child_high = avg + beta * diff # Preserve the parent identity: the child that stepped down belongs to whichever parent # held the smaller value, as in Deb's reference implementation and in pymoo. first_is_lower = mating_pop[i] <= mating_pop[i + 1] offspring[i] = np.where(first_is_lower, child_low, child_high) offspring[i + 1] = np.where(first_is_lower, child_high, child_low) # Decision variables not selected for SBX are inherited unchanged. This has to be an # explicit copy rather than a beta = 1 sentinel: with the sorted difference above, beta = 1 # would hand every untouched variable's smaller value to offspring i and the larger to # offspring i + 1, biasing the pair instead of leaving it alone. # jMetal exchanges them between the offspring instead; see `swap_uncrossed_variables`. first, second = (i + 1, i) if self.swap_uncrossed_variables else (i, i + 1) offspring[i, ~sbx_mask] = mating_pop[first, ~sbx_mask] offspring[i + 1, ~sbx_mask] = mating_pop[second, ~sbx_mask] # Swap the offspring for decision variables where binary crossover is applied offspring[i, binary_mask], offspring[i + 1, binary_mask] = ( offspring[i + 1, binary_mask].copy(), offspring[i, binary_mask].copy(), ) # The mathematics above already keeps the offspring feasible; this only absorbs floating point # drift at the bounds. Every reference implementation of truncated SBX clamps here as well. offspring = np.clip(offspring, lower_bounds, upper_bounds) return pl.from_numpy(offspring, schema=self.variable_symbols, orient="row") def update(self, *_, **__): """Do nothing. This is just the basic SBX operator.""" def state(self) -> Sequence[Message]: """Return the state of the crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source="SimulatedBinaryCrossover", value=self.xover_probability, ), FloatMessage( topic=CrossoverMessageTopics.XOVER_DISTRIBUTION, source="SimulatedBinaryCrossover", value=self.xover_distribution, ), ] # verbosity == 2 or higher return [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source="SimulatedBinaryCrossover", value=self.xover_probability, ), FloatMessage( topic=CrossoverMessageTopics.XOVER_DISTRIBUTION, source="SimulatedBinaryCrossover", value=self.xover_distribution, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source="SimulatedBinaryCrossover", value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source="SimulatedBinaryCrossover", value=self.offspring_population, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics the crossover operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the crossover operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, pair_xover_probability: float = 1.0, xover_probability: float = 0.5, uniform_xover_probability: float = 0.5, xover_distribution: float = 30, truncated: bool = True, swap_uncrossed_variables: bool = False, ) ``` Initialize a simulated binary crossover operator. Parameters: | Name | Type | Description | Default | | --------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `seed` | `int` | the seed for the random number generator. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | | `pair_xover_probability` | `float` | the probability that a parent pair is recombined at all. Drawn once per pair: on failure the pair is copied to the offspring unchanged, with every decision variable kept together. This is the p_c reported in the literature (1.0 in the RVEA and NSGA-III papers, 0.9 in NSGA-II). Ranges between 0 and 1.0. Defaults to 1.0. | `1.0` | | `xover_probability` | `float` | the per-variable crossover probability. Drawn once per decision variable, and decides whether the SBX operation is performed on that variable. Ranges between 0 and 1.0. Defaults to 0.5, following Deb and Agrawal (1995), who state "we choose to perform SBX in each variable with probability 0.5". Note this is a separate level from pair_xover_probability: the literature's p_c = 1.0 refers to the pair, not to the variable, so it belongs in pair_xover_probability. | `0.5` | | `uniform_xover_probability` | `float` | the uniform crossover probability parameter. This parameter decides whether the decision variable components of the parents are swapped for the offspring or not. Ranges between 0 and 1.0. Defaults to 0.5. Only operates on variables that have already been selected for crossover by the xover_probability parameter. | `0.5` | | `xover_distribution` | `float` | the crossover distribution parameter. Must be positive. This parameter controls the distribution of the offspring. A larger value results in a distribution that is more concentrated around the parents, while a smaller value results in a distribution that is more spread out. Defaults to 30. | `30` | | `truncated` | `bool` | whether to truncate the probability distribution to keep the offspring within the variable bounds. Defaults to True. | `True` | | `swap_uncrossed_variables` | `bool` | whether a decision variable not selected by xover_probability is exchanged between the two offspring instead of inherited unchanged. Defaults to False, which is what every implementation surveyed does except jMetal (Java). jMetal's else-branch assigns offspring1[i] = parent2[i] and offspring2[i] = parent1[i], adding a genuine uniform-crossover component on top of SBX: at the standard per-variable rate of 0.5, half of the genome is swapped wholesale every time a pair recombines. Set it to reproduce jMetal; leave it alone otherwise. | `False` | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, pair_xover_probability: float = 1.0, xover_probability: float = 0.5, uniform_xover_probability: float = 0.5, xover_distribution: float = 30, truncated: bool = True, swap_uncrossed_variables: bool = False, ): """Initialize a simulated binary crossover operator. Args: problem (Problem): the problem object. seed (int): the seed for the random number generator. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. pair_xover_probability (float, optional): the probability that a parent pair is recombined at all. Drawn once per pair: on failure the pair is copied to the offspring unchanged, with every decision variable kept together. This is the `p_c` reported in the literature (1.0 in the RVEA and NSGA-III papers, 0.9 in NSGA-II). Ranges between 0 and 1.0. Defaults to 1.0. xover_probability (float, optional): the per-variable crossover probability. Drawn once per decision variable, and decides whether the SBX operation is performed on that variable. Ranges between 0 and 1.0. Defaults to 0.5, following Deb and Agrawal (1995), who state "we choose to perform SBX in each variable with probability 0.5". Note this is a *separate* level from `pair_xover_probability`: the literature's `p_c = 1.0` refers to the pair, not to the variable, so it belongs in `pair_xover_probability`. uniform_xover_probability (float, optional): the uniform crossover probability parameter. This parameter decides whether the decision variable components of the parents are swapped for the offspring or not. Ranges between 0 and 1.0. Defaults to 0.5. Only operates on variables that have already been selected for crossover by the xover_probability parameter. xover_distribution (float, optional): the crossover distribution parameter. Must be positive. This parameter controls the distribution of the offspring. A larger value results in a distribution that is more concentrated around the parents, while a smaller value results in a distribution that is more spread out. Defaults to 30. truncated (bool, optional): whether to truncate the probability distribution to keep the offspring within the variable bounds. Defaults to True. swap_uncrossed_variables (bool, optional): whether a decision variable *not* selected by `xover_probability` is exchanged between the two offspring instead of inherited unchanged. Defaults to False, which is what every implementation surveyed does except jMetal (Java). jMetal's else-branch assigns `offspring1[i] = parent2[i]` and `offspring2[i] = parent1[i]`, adding a genuine uniform-crossover component on top of SBX: at the standard per-variable rate of 0.5, half of the genome is swapped wholesale every time a pair recombines. Set it to reproduce jMetal; leave it alone otherwise. """ # Subscribes to no topics, so no need to stroe/pass the topics to the super class. super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) self.problem = problem if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("SimulatedBinaryCrossover only works on continuous problems.") if not 0 <= pair_xover_probability <= 1: raise ValueError("Pair crossover probability must be between 0 and 1.") if not 0 <= xover_probability <= 1: raise ValueError("Crossover probability must be between 0 and 1.") if xover_distribution <= 0: raise ValueError("Crossover distribution must be positive.") self.pair_xover_probability = pair_xover_probability self.xover_probability = xover_probability self.xover_distribution = xover_distribution self.uniform_xover_probability = uniform_xover_probability self.truncated = truncated self.swap_uncrossed_variables = swap_uncrossed_variables ``` ##### bounded_offsprings ``` bounded_offsprings( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform the bounded simulated binary crossover operation. This implementation is similar to pymoo and boundedSBX in deap. One of the first papers I can find that actually describes how to calculate it is [1]. The basic idea is as follows: 1. Take the probability distributions of the unbounded SBX operator. There are two: one for the contracting case (mu \<= 0.5, beta \<= 1) and one for the expanding case (mu > 0.5, beta > 1). 1. Assume that we are bounded on the lower side. Calculate a maximum value of beta such that any potential offspring will not be below the lower bound. This is done by solving for beta in the equation: c = (p1+p2)/2 - beta\*(p1-p2)/2, where c is the child (or in this case, the lower bound), p1 and p2 are parents. Thus, beta_max = (p1+p2-2\*c)/(p1-p2). This is the maximum value of beta such that the child will still be above the lower bound. In most implementations, this is called beta_q, and the equation is slightly rearranged to be beta_q = 1 + 2\*(p1-x_L)/(p2-p1), where p1\ pl.DataFrame: """Perform the bounded simulated binary crossover operation. This implementation is similar to pymoo and boundedSBX in deap. One of the first papers I can find that actually describes how to calculate it is [1]. The basic idea is as follows: 1. Take the probability distributions of the unbounded SBX operator. There are two: one for the contracting case (mu <= 0.5, beta <= 1) and one for the expanding case (mu > 0.5, beta > 1). 2. Assume that we are bounded on the lower side. Calculate a maximum value of beta such that any potential offspring will not be below the lower bound. This is done by solving for beta in the equation: c = (p1+p2)/2 - beta*(p1-p2)/2, where c is the child (or in this case, the lower bound), p1 and p2 are parents. Thus, beta_max = (p1+p2-2*c)/(p1-p2). This is the maximum value of beta such that the child will still be above the lower bound. In most implementations, this is called beta_q, and the equation is slightly rearranged to be beta_q = 1 + 2*(p1-x_L)/(p2-p1), where p1 self.pair_xover_probability: offspring[i] = mating_pop[i] offspring[i + 1] = mating_pop[i + 1] continue beta = np.zeros(num_var) miu = self.rng.random(num_var) # Apply crossover only for certain decision variables sbx_mask = self.rng.random(num_var) <= self.xover_probability # Apply binary crossover only for certain decision variables binary_mask = self.rng.random(num_var) <= self.uniform_xover_probability binary_mask = binary_mask & sbx_mask # Only apply binary crossover where SBX is applied avg = (mating_pop[i] + mating_pop[i + 1]) / 2 x1 = np.minimum(mating_pop[i], mating_pop[i + 1]) x2 = np.maximum(mating_pop[i], mating_pop[i + 1]) # The two children are derived in *sorted* order: one steps from the midpoint down towards # the lower bound, the other up towards the upper bound, and each uses the beta capped by # the distance to the bound it is stepping towards. The half-difference must therefore be # taken between the sorted values, not between the parents in whatever order the mating # pool happens to hold them. Using the unsorted difference pairs the lower-bound beta with # an upward step (and vice versa) whenever mating_pop[i] is the smaller parent, which lets # the offspring escape the variable bounds. diff = (x2 - x1) / 2 # Child stepping towards the lower bound. with np.errstate(divide="ignore", invalid="ignore"): # Handles x1 == x2 case beta_max = 1 + 2 * (x1 - lower_bounds) / (x2 - x1) beta_max[np.isnan(beta_max)] = np.inf # Handles x1 == x2 == lower_bound case # Technically, this code can handle the unbounded case by setting alpha to an array of 2s. alpha = 2 - (1 / beta_max) ** (self.xover_distribution + 1) SPLIT_POINT1 = 1 / alpha # NOQA: N806 beta[miu <= SPLIT_POINT1] = (alpha[miu <= SPLIT_POINT1] * miu[miu <= SPLIT_POINT1]) ** ( 1 / (self.xover_distribution + 1) ) beta[miu > SPLIT_POINT1] = (2 - alpha[miu > SPLIT_POINT1] * miu[miu > SPLIT_POINT1]) ** ( -1 / (self.xover_distribution + 1) ) # Turning beta negative does not work for truncated SBX. Manually swap the offspring instead. child_low = avg - beta * diff # Child stepping towards the upper bound. The same miu is reused deliberately: every # reference implementation draws one uniform per variable and shares it between the two # children, so that the pair is perfectly correlated. with np.errstate(divide="ignore", invalid="ignore"): # Handles x1 == x2 case beta_max = 1 + 2 * (upper_bounds - x2) / (x2 - x1) beta_max[np.isnan(beta_max)] = np.inf # Handles x1 == x2 == upper_bound case # The error states only occur when x1==x2, which means that the parents are equal, and thus the offspring # will be equal to the parents. So, np.inf is fine. alpha = 2 - (1 / beta_max) ** (self.xover_distribution + 1) SPLIT_POINT2 = 1 / alpha # NOQA: N806 beta[miu <= SPLIT_POINT2] = (alpha[miu <= SPLIT_POINT2] * miu[miu <= SPLIT_POINT2]) ** ( 1 / (self.xover_distribution + 1) ) beta[miu > SPLIT_POINT2] = (2 - alpha[miu > SPLIT_POINT2] * miu[miu > SPLIT_POINT2]) ** ( -1 / (self.xover_distribution + 1) ) child_high = avg + beta * diff # Preserve the parent identity: the child that stepped down belongs to whichever parent # held the smaller value, as in Deb's reference implementation and in pymoo. first_is_lower = mating_pop[i] <= mating_pop[i + 1] offspring[i] = np.where(first_is_lower, child_low, child_high) offspring[i + 1] = np.where(first_is_lower, child_high, child_low) # Decision variables not selected for SBX are inherited unchanged. This has to be an # explicit copy rather than a beta = 1 sentinel: with the sorted difference above, beta = 1 # would hand every untouched variable's smaller value to offspring i and the larger to # offspring i + 1, biasing the pair instead of leaving it alone. # jMetal exchanges them between the offspring instead; see `swap_uncrossed_variables`. first, second = (i + 1, i) if self.swap_uncrossed_variables else (i, i + 1) offspring[i, ~sbx_mask] = mating_pop[first, ~sbx_mask] offspring[i + 1, ~sbx_mask] = mating_pop[second, ~sbx_mask] # Swap the offspring for decision variables where binary crossover is applied offspring[i, binary_mask], offspring[i + 1, binary_mask] = ( offspring[i + 1, binary_mask].copy(), offspring[i, binary_mask].copy(), ) # The mathematics above already keeps the offspring feasible; this only absorbs floating point # drift at the bounds. Every reference implementation of truncated SBX clamps here as well. offspring = np.clip(offspring, lower_bounds, upper_bounds) return pl.from_numpy(offspring, schema=self.variable_symbols, orient="row") ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform the simulated binary crossover operation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | --------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform the simulated binary crossover operation. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ if self.truncated: offspring = self.bounded_offsprings(population=population, to_mate=to_mate) else: offspring = self.unbounded_offsprings(population=population, to_mate=to_mate) # An odd sized mating pool was padded with a duplicate parent, so the last pair produced one # offspring too many. original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] if original_pop_size % 2 == 1: offspring = offspring.head(original_pop_size) self.offspring_population = offspring self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source="SimulatedBinaryCrossover", value=self.xover_probability, ), FloatMessage( topic=CrossoverMessageTopics.XOVER_DISTRIBUTION, source="SimulatedBinaryCrossover", value=self.xover_distribution, ), ] # verbosity == 2 or higher return [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source="SimulatedBinaryCrossover", value=self.xover_probability, ), FloatMessage( topic=CrossoverMessageTopics.XOVER_DISTRIBUTION, source="SimulatedBinaryCrossover", value=self.xover_distribution, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source="SimulatedBinaryCrossover", value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source="SimulatedBinaryCrossover", value=self.offspring_population, ), ] ``` ##### unbounded_offsprings ``` unbounded_offsprings( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform the unbounded simulated binary crossover operation. Implementation based on Deb, Kalyanmoy, and Ram Bhushan Agrawal. "Simulated binary crossover for continuous search space." Complex systems 9.2 (1995): 115-148. This implementation follows PlatEMO's `OperatorGA`. DEAP's `cxSimulatedBinary` derives the same beta, but omits the random sign and the per-variable mask that PlatEMO adds on top of the paper. pymoo, DEAP's `cxSimulatedBinaryBounded`, jMetalPy, Platypus, pagmo2 and Deb's own NSGA-II C code all implement the truncated/bounded variant while calling it simulated binary crossover; see `bounded_offsprings` for that one. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | --------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def unbounded_offsprings( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform the unbounded simulated binary crossover operation. Implementation based on Deb, Kalyanmoy, and Ram Bhushan Agrawal. "Simulated binary crossover for continuous search space." Complex systems 9.2 (1995): 115-148. This implementation follows PlatEMO's `OperatorGA`. DEAP's `cxSimulatedBinary` derives the same beta, but omits the random sign and the per-variable mask that PlatEMO adds on top of the paper. pymoo, DEAP's `cxSimulatedBinaryBounded`, jMetalPy, Platypus, pagmo2 and Deb's own NSGA-II C code all implement the truncated/bounded variant while calling it simulated binary crossover; see `bounded_offsprings` for that one. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy().astype(float) mate_size = mating_pop.shape[0] num_var = mating_pop.shape[1] offspring = np.zeros_like(mating_pop) HALF = 0.5 # NOQA: N806 # TODO(@light-weaver): Extract into a numba jitted function. for i in range(0, mate_size, 2): # One draw per pair, before any per-variable draw. A pair that fails is copied whole, so # all of its variables stay together -- that within-pair correlation is the point, and is # what folding p_c into the per-variable rate would destroy. if self.rng.random() > self.pair_xover_probability: offspring[i] = mating_pop[i] offspring[i + 1] = mating_pop[i + 1] continue beta = np.zeros(num_var) miu = self.rng.random(num_var) # Simulated binary crossover (SBX) operator tries to mimic the behavior of single-point crossover by # trying to attain similar distribution of offspring as single-point crossover. # The distribution itself can be contracting or expanding. # beta is calculated such that the integral (over (0, beta)) of the distribution matches the random number # mu. At mu <= 0.5, the distribution is contracting, and at mu > 0.5, the distribution is expanding. # You can integrate equations 18 and 19 from the reference in the docstring to see how the equations below # are derived. Integrate 18 from 0 to beta, and set it equal to mu. Solve for beta. # for 19, first integrate 18 from 0 to 1 (which is equal to 0.5 so you don't actually need to integrate it) # Then add the integral of 19 from 1 to beta, and set it equal to mu. Solve for beta. beta[miu <= HALF] = (2 * miu[miu <= HALF]) ** (1 / (self.xover_distribution + 1)) # 18 beta[miu > HALF] = (2 - 2 * miu[miu > HALF]) ** (-1 / (self.xover_distribution + 1)) # 18 + 19 # if beta is negative, the offspring 1 gets decision var component closer to parent 2 and vice versa. # In this implementation, there is an equal chance of beta being negative or positive. # TBH, this is more similar to uniform crossover than single-point crossover. binary_mask = self.rng.random(num_var) <= self.uniform_xover_probability binary_mask = (binary_mask * 2) - 1 # Convert to -1 or 1 beta = beta * binary_mask # At beta = -1 no crossover occurs and the dec var components are copied from the parents: # offspring[i] = avg + diff = mating_pop[i]. (Beta = +1 would swap the parents instead, # which is what PlatEMO's opposite sign convention on the offspring expression means by # setting the sentinel to +1 there.) # jMetal wants exactly that swap on the uncrossed variables, so the sentinel flips sign. uncrossed_sentinel = 1 if self.swap_uncrossed_variables else -1 beta[self.rng.random(num_var) > self.xover_probability] = uncrossed_sentinel # Note that when mu < 0.5, abs(beta) ends up being less than 1, resulting in a contracting crossover. # The opposite is true when mu > 0.5, resulting in an expanding crossover. avg = (mating_pop[i] + mating_pop[i + 1]) / 2 diff = (mating_pop[i] - mating_pop[i + 1]) / 2 offspring[i] = avg - beta * diff offspring[i + 1] = avg + beta * diff # Clip the offspring to the bounds lower_bounds = np.asarray(self.lower_bounds, dtype=float) upper_bounds = np.asarray(self.upper_bounds, dtype=float) offspring = np.clip(offspring, lower_bounds, upper_bounds) return pl.from_numpy(offspring, schema=self.variable_symbols, orient="row") ``` ##### update ``` update(*_, **__) ``` Do nothing. This is just the basic SBX operator. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing. This is just the basic SBX operator.""" ``` #### SingleArithmeticCrossover Bases: `BaseCrossover` Single Arithmetic Crossover for continuous problems. One decision variable is picked per mating pair and replaced in both offspring by the average of the two parent values. Every other variable is inherited unchanged from the respective parent, so each offspring differs from its own parent in exactly one position. References Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 Source code in `desdeo/emo/operators/crossover.py` ``` class SingleArithmeticCrossover(BaseCrossover): """Single Arithmetic Crossover for continuous problems. One decision variable is picked per mating pair and replaced in both offspring by the average of the two parent values. Every other variable is inherited unchanged from the respective parent, so each offspring differs from its own parent in exactly one position. References: Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 """ @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the single arithmetic crossover operator.""" return { 0: [], # No topics for 0 1: [ CrossoverMessageTopics.XOVER_PROBABILITY, # Probability of crossover ], 2: [ CrossoverMessageTopics.XOVER_PROBABILITY, # Crossover probability CrossoverMessageTopics.PARENTS, # Parents involved in crossover CrossoverMessageTopics.OFFSPRINGS, # Offsprings created from crossover ], } @property def interested_topics(self): """The message topics that the single arithmetic crossover operator is interested in.""" return [] def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, seed: int, xover_probability: float = 1.0, ): """Initialize the single arithmetic crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. xover_probability (float): probability of performing crossover. seed (int): random seed for reproducibility. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("SingleArithmeticCrossover only works on continuous problems.") if not 0 <= xover_probability <= 1: raise ValueError("Crossover probability must be in [0, 1].") self.xover_probability = xover_probability def do(self, *, population: pl.DataFrame, to_mate: list[int] | None = None) -> pl.DataFrame: """Perform Single Arithmetic Crossover. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pool = self.get_parents(population=population, to_mate=to_mate) mating_pool = mating_pool[self.variable_symbols].to_numpy().astype(float) mating_pop_size = mating_pool.shape[0] num_vars = mating_pool.shape[1] original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] parents1 = mating_pool[0::2, :] parents2 = mating_pool[1::2, :] mask = self.rng.random(mating_pop_size // 2) <= self.xover_probability gene_pos = self.rng.integers(0, num_vars, size=mating_pop_size // 2) # Initialize offspring as exact copies offspring1 = parents1.copy() offspring2 = parents2.copy() # Apply crossover only for selected pairs row_idx = np.arange(len(mask))[mask] col_idx = gene_pos[mask] avg = 0.5 * (parents1[row_idx, col_idx] + parents2[row_idx, col_idx]) offspring1[row_idx, col_idx] = avg offspring2[row_idx, col_idx] = avg offspring = np.vstack((offspring1, offspring2)) if original_pop_size % 2 == 1: offspring = offspring[:-1, :] self.offspring_population = pl.from_numpy(offspring, schema=self.variable_symbols, orient="row").select( pl.all().cast(pl.Float64) ) self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the single arithmetic crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] # Messages for crossover probability if self.verbosity >= 1: msgs.append( FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.xover_probability, ) ) # Messages for parents and offspring if self.verbosity >= 2: # noqa: PLR2004 - more detailed info msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### interested_topics ``` interested_topics ``` The message topics that the single arithmetic crossover operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the single arithmetic crossover operator. ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, seed: int, xover_probability: float = 1.0, ) ``` Initialize the single arithmetic crossover operator. Parameters: | Name | Type | Description | Default | | ------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | | `xover_probability` | `float` | probability of performing crossover. | `1.0` | | `seed` | `int` | random seed for reproducibility. | *required* | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, seed: int, xover_probability: float = 1.0, ): """Initialize the single arithmetic crossover operator. Args: problem (Problem): the problem object. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. xover_probability (float): probability of performing crossover. seed (int): random seed for reproducibility. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("SingleArithmeticCrossover only works on continuous problems.") if not 0 <= xover_probability <= 1: raise ValueError("Crossover probability must be in [0, 1].") self.xover_probability = xover_probability ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform Single Arithmetic Crossover. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | --------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do(self, *, population: pl.DataFrame, to_mate: list[int] | None = None) -> pl.DataFrame: """Perform Single Arithmetic Crossover. Args: population (pl.DataFrame): the population to perform the crossover with. The DataFrame contains the decision vectors, the target vectors, and the constraint vectors. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pool = self.get_parents(population=population, to_mate=to_mate) mating_pool = mating_pool[self.variable_symbols].to_numpy().astype(float) mating_pop_size = mating_pool.shape[0] num_vars = mating_pool.shape[1] original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] parents1 = mating_pool[0::2, :] parents2 = mating_pool[1::2, :] mask = self.rng.random(mating_pop_size // 2) <= self.xover_probability gene_pos = self.rng.integers(0, num_vars, size=mating_pop_size // 2) # Initialize offspring as exact copies offspring1 = parents1.copy() offspring2 = parents2.copy() # Apply crossover only for selected pairs row_idx = np.arange(len(mask))[mask] col_idx = gene_pos[mask] avg = 0.5 * (parents1[row_idx, col_idx] + parents2[row_idx, col_idx]) offspring1[row_idx, col_idx] = avg offspring2[row_idx, col_idx] = avg offspring = np.vstack((offspring1, offspring2)) if original_pop_size % 2 == 1: offspring = offspring[:-1, :] self.offspring_population = pl.from_numpy(offspring, schema=self.variable_symbols, orient="row").select( pl.all().cast(pl.Float64) ) self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the single arithmetic crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the single arithmetic crossover operator.""" if self.parent_population is None: return [] msgs: list[Message] = [] # Messages for crossover probability if self.verbosity >= 1: msgs.append( FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.xover_probability, ) ) # Messages for parents and offspring if self.verbosity >= 2: # noqa: PLR2004 - more detailed info msgs.extend( [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ) return msgs ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### SinglePointBinaryCrossover Bases: `BaseCrossover` A class that defines the single point binary crossover operation. A crossover point is drawn uniformly from the positions that actually split the parents, and the two offspring take the genes before the point from one parent and the rest from the other. References Holland, J. H. (1975). Adaptation in Natural and Artificial Systems. University of Michigan Press. Goldberg, D. E. (1989). Genetic Algorithms in Search, Optimization and Machine Learning. Addison-Wesley. Source code in `desdeo/emo/operators/crossover.py` ``` class SinglePointBinaryCrossover(BaseCrossover): """A class that defines the single point binary crossover operation. A crossover point is drawn uniformly from the positions that actually split the parents, and the two offspring take the genes before the point from one parent and the rest from the other. References: Holland, J. H. (1975). Adaptation in Natural and Artificial Systems. University of Michigan Press. Goldberg, D. E. (1989). Genetic Algorithms in Search, Optimization and Machine Learning. Addison-Wesley. """ def __init__(self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher): """Initialize the single point binary crossover operator. Args: problem (Problem): the problem object. seed (int): the seed used in the random number generator for choosing the crossover point. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. publisher (Publisher): the publisher to which the operator will publish messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the single point binary crossover operator.""" return { 0: [], 1: [], 2: [ CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics the single point binary crossover operator is interested in.""" return [] def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform single point binary crossover. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None, optional): indices. Defaults to None. Returns: pl.DataFrame: the offspring from the crossover. """ self.parent_population = population pop_size = self.parent_population.shape[0] num_var = len(self.variable_symbols) if num_var < 2: # noqa: PLR2004 raise ValueError( f"Single point binary crossover needs at least two decision variables, but the problem has {num_var}." ) parent_decision_vars = self.parent_population[self.variable_symbols].to_numpy().astype(np.bool) if to_mate is None: shuffled_ids = list(range(pop_size)) self.rng.shuffle(shuffled_ids) else: shuffled_ids = copy.copy(to_mate) mating_pop = parent_decision_vars[shuffled_ids] mating_pop_size = len(shuffled_ids) original_mating_pop_size = mating_pop_size if mating_pop_size % 2 != 0: # if the number of member to mate is of uneven size, copy the first member to the tail mating_pop = np.vstack((mating_pop, mating_pop[0])) mating_pop_size += 1 shuffled_ids.append(shuffled_ids[0]) # split the population into parents, one with members with even numbered indices, the # other with uneven numbered indices parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] # The high value of rng.integers is exclusive. cross_over_points = self.rng.integers(1, num_var, mating_pop_size // 2) # create a mask where, on each row, the element is 1 before the crossover point, # and zero after it cross_over_mask = np.zeros_like(parents1, dtype=np.bool) cross_over_mask[np.arange(cross_over_mask.shape[1]) < cross_over_points[:, None]] = 1 # pick genes from the first parents before the crossover point # pick genes from the second parents after, and including, the crossover point offspring1_first = cross_over_mask & parents1 offspring1_second = (~cross_over_mask) & parents2 # combine into a first half of the whole offspring population offspring1 = offspring1_first | offspring1_second # pick genes from the first parents after, and including, the crossover point # pick genes from the second parents before the crossover point offspring2_first = (~cross_over_mask) & parents1 offspring2_second = cross_over_mask & parents2 # combine into the second half of the whole offspring population offspring2 = offspring2_first | offspring2_second # combine the two offspring populations into one, drop the last member if the number of # indices (to_mate) is uneven self.offspring_population = pl.from_numpy( np.vstack((offspring1, offspring2))[ : (original_mating_pop_size if original_mating_pop_size % 2 == 0 else -1) ], schema=self.variable_symbols, orient="row", ).select(pl.all().cast(pl.Float64)) self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing. This is just the basic single point binary crossover operator.""" def state(self) -> Sequence[Message]: """Return the state of the single ponit binary crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [] # verbosity == 2 or higher return [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics the single point binary crossover operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the single point binary crossover operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, ) ``` Initialize the single point binary crossover operator. Parameters: | Name | Type | Description | Default | | ----------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `seed` | `int` | the seed used in the random number generator for choosing the crossover point. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__(self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher): """Initialize the single point binary crossover operator. Args: problem (Problem): the problem object. seed (int): the seed used in the random number generator for choosing the crossover point. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. publisher (Publisher): the publisher to which the operator will publish messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform single point binary crossover. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | --------------------------------------------- | -------------------------- | | `population` | `DataFrame` | the population to perform the crossover with. | *required* | | `to_mate` | \`list[int] | None\` | indices. Defaults to None. | Returns: | Type | Description | | ----------- | ----------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform single point binary crossover. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None, optional): indices. Defaults to None. Returns: pl.DataFrame: the offspring from the crossover. """ self.parent_population = population pop_size = self.parent_population.shape[0] num_var = len(self.variable_symbols) if num_var < 2: # noqa: PLR2004 raise ValueError( f"Single point binary crossover needs at least two decision variables, but the problem has {num_var}." ) parent_decision_vars = self.parent_population[self.variable_symbols].to_numpy().astype(np.bool) if to_mate is None: shuffled_ids = list(range(pop_size)) self.rng.shuffle(shuffled_ids) else: shuffled_ids = copy.copy(to_mate) mating_pop = parent_decision_vars[shuffled_ids] mating_pop_size = len(shuffled_ids) original_mating_pop_size = mating_pop_size if mating_pop_size % 2 != 0: # if the number of member to mate is of uneven size, copy the first member to the tail mating_pop = np.vstack((mating_pop, mating_pop[0])) mating_pop_size += 1 shuffled_ids.append(shuffled_ids[0]) # split the population into parents, one with members with even numbered indices, the # other with uneven numbered indices parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] # The high value of rng.integers is exclusive. cross_over_points = self.rng.integers(1, num_var, mating_pop_size // 2) # create a mask where, on each row, the element is 1 before the crossover point, # and zero after it cross_over_mask = np.zeros_like(parents1, dtype=np.bool) cross_over_mask[np.arange(cross_over_mask.shape[1]) < cross_over_points[:, None]] = 1 # pick genes from the first parents before the crossover point # pick genes from the second parents after, and including, the crossover point offspring1_first = cross_over_mask & parents1 offspring1_second = (~cross_over_mask) & parents2 # combine into a first half of the whole offspring population offspring1 = offspring1_first | offspring1_second # pick genes from the first parents after, and including, the crossover point # pick genes from the second parents before the crossover point offspring2_first = (~cross_over_mask) & parents1 offspring2_second = cross_over_mask & parents2 # combine into the second half of the whole offspring population offspring2 = offspring2_first | offspring2_second # combine the two offspring populations into one, drop the last member if the number of # indices (to_mate) is uneven self.offspring_population = pl.from_numpy( np.vstack((offspring1, offspring2))[ : (original_mating_pop_size if original_mating_pop_size % 2 == 0 else -1) ], schema=self.variable_symbols, orient="row", ).select(pl.all().cast(pl.Float64)) self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the single ponit binary crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the single ponit binary crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [] # verbosity == 2 or higher return [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. This is just the basic single point binary crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing. This is just the basic single point binary crossover operator.""" ``` #### UniformCrossover Bases: `BaseCrossover` Uniform (discrete) crossover for continuous problems. Every decision variable is inherited whole from one parent or the other, with the two offspring taking complementary choices. `UniformMixedIntegerCrossover` performs the same recombination without a domain guard and is therefore usable on continuous problems, but it fixes the per-variable rate at 0.5, offers no per-pair probability. References Syswerda, G. (1989). Uniform crossover in genetic algorithms. In Proceedings of the Third International Conference on Genetic Algorithms (pp. 2-9). Morgan Kaufmann. Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 (Empirical comparison of discrete crossover against the blending operators.) Source code in `desdeo/emo/operators/crossover.py` ``` class UniformCrossover(BaseCrossover): """Uniform (discrete) crossover for continuous problems. Every decision variable is inherited whole from one parent or the other, with the two offspring taking complementary choices. `UniformMixedIntegerCrossover` performs the same recombination without a domain guard and is therefore usable on continuous problems, but it fixes the per-variable rate at 0.5, offers no per-pair probability. References: Syswerda, G. (1989). Uniform crossover in genetic algorithms. In Proceedings of the Third International Conference on Genetic Algorithms (pp. 2-9). Morgan Kaufmann. Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 (Empirical comparison of discrete crossover against the blending operators.) """ def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, pair_xover_probability: float = 1.0, uniform_xover_probability: float = 0.5, ): """Initialize a uniform crossover operator. Args: problem (Problem): the problem object. seed (int): the seed for the random number generator. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. publisher (Publisher): the publisher to which the operator will publish messages. pair_xover_probability (float, optional): the probability that a parent pair is recombined at all. Drawn once per pair: on failure the pair is copied to the offspring unchanged, with every decision variable kept together. This is the `p_c` reported in the literature. Ranges between 0 and 1.0. Defaults to 1.0. uniform_xover_probability (float, optional): the per-variable probability that the two parents' values for that variable are exchanged between the offspring. Ranges between 0 and 1.0. Defaults to 0.5, the rate Syswerda (1989) describes and the only rate `UniformMixedIntegerCrossover` offers. Named to match the parameter of the same meaning on `SimulatedBinaryCrossover`, so the two can be set to the same value and compared. At 0.0 the offspring are copies of the parents; at 1.0 the pair is swapped wholesale, which is also a no-op at the population level. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) self.problem = problem if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("UniformCrossover only works on continuous problems.") if not 0 <= pair_xover_probability <= 1: raise ValueError("Pair crossover probability must be between 0 and 1.") if not 0 <= uniform_xover_probability <= 1: raise ValueError("Uniform crossover probability must be between 0 and 1.") self.pair_xover_probability = pair_xover_probability self.uniform_xover_probability = uniform_xover_probability self.parent_population: pl.DataFrame | None = None self.offspring_population: pl.DataFrame | None = None @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the uniform crossover operator.""" return { 0: [], 1: [CrossoverMessageTopics.XOVER_PROBABILITY], 2: [ CrossoverMessageTopics.XOVER_PROBABILITY, CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics the uniform crossover operator is interested in.""" return [] def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform the uniform crossover operation. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy().astype(float) num_var = mating_pop.shape[1] parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] n_pairs = parents1.shape[0] # One independent mask per mating pair. A single mask of shape (num_var,) would broadcast over # the whole mating pool, making every pair in the generation exchange exactly the same # variables -- a fixed column split rather than uniform crossover. swap = self.rng.random((n_pairs, num_var)) < self.uniform_xover_probability # The per-pair draw comes first and covers the whole row, so a pair that fails keeps its # variables together. Folding it into the per-variable rate would destroy that correlation, # which is the reason the two levels are separate. recombined = self.rng.random(n_pairs) <= self.pair_xover_probability swap &= recombined[:, np.newaxis] offspring1 = np.where(swap, parents2, parents1) offspring2 = np.where(swap, parents1, parents2) offspring = np.vstack((offspring1, offspring2)) # An odd sized mating pool was padded with a duplicate parent, so the last pair produced one # offspring too many. original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] offspring = offspring[:original_pop_size] self.offspring_population = pl.from_numpy(offspring, schema=self.variable_symbols, orient="row") self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing. The operator has no state that reacts to other components.""" def state(self) -> Sequence[Message]: """Return the state of the uniform crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.uniform_xover_probability, ), ] # verbosity == 2 or higher return [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.uniform_xover_probability, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics the uniform crossover operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the uniform crossover operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, pair_xover_probability: float = 1.0, uniform_xover_probability: float = 0.5, ) ``` Initialize a uniform crossover operator. Parameters: | Name | Type | Description | Default | | --------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `seed` | `int` | the seed for the random number generator. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | | `pair_xover_probability` | `float` | the probability that a parent pair is recombined at all. Drawn once per pair: on failure the pair is copied to the offspring unchanged, with every decision variable kept together. This is the p_c reported in the literature. Ranges between 0 and 1.0. Defaults to 1.0. | `1.0` | | `uniform_xover_probability` | `float` | the per-variable probability that the two parents' values for that variable are exchanged between the offspring. Ranges between 0 and 1.0. Defaults to 0.5, the rate Syswerda (1989) describes and the only rate UniformMixedIntegerCrossover offers. Named to match the parameter of the same meaning on SimulatedBinaryCrossover, so the two can be set to the same value and compared. At 0.0 the offspring are copies of the parents; at 1.0 the pair is swapped wholesale, which is also a no-op at the population level. | `0.5` | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, pair_xover_probability: float = 1.0, uniform_xover_probability: float = 0.5, ): """Initialize a uniform crossover operator. Args: problem (Problem): the problem object. seed (int): the seed for the random number generator. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. publisher (Publisher): the publisher to which the operator will publish messages. pair_xover_probability (float, optional): the probability that a parent pair is recombined at all. Drawn once per pair: on failure the pair is copied to the offspring unchanged, with every decision variable kept together. This is the `p_c` reported in the literature. Ranges between 0 and 1.0. Defaults to 1.0. uniform_xover_probability (float, optional): the per-variable probability that the two parents' values for that variable are exchanged between the offspring. Ranges between 0 and 1.0. Defaults to 0.5, the rate Syswerda (1989) describes and the only rate `UniformMixedIntegerCrossover` offers. Named to match the parameter of the same meaning on `SimulatedBinaryCrossover`, so the two can be set to the same value and compared. At 0.0 the offspring are copies of the parents; at 1.0 the pair is swapped wholesale, which is also a no-op at the population level. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) self.problem = problem if problem.variable_domain is not VariableDomainTypeEnum.continuous: raise ValueError("UniformCrossover only works on continuous problems.") if not 0 <= pair_xover_probability <= 1: raise ValueError("Pair crossover probability must be between 0 and 1.") if not 0 <= uniform_xover_probability <= 1: raise ValueError("Uniform crossover probability must be between 0 and 1.") self.pair_xover_probability = pair_xover_probability self.uniform_xover_probability = uniform_xover_probability self.parent_population: pl.DataFrame | None = None self.offspring_population: pl.DataFrame | None = None ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform the uniform crossover operation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `population` | `DataFrame` | the population to perform the crossover with. | *required* | | `to_mate` | \`list[int] | None\` | the indices of the population members that should participate in the crossover. If None, the whole population is subject to the crossover. | Returns: | Type | Description | | ----------- | --------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform the uniform crossover operation. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None): the indices of the population members that should participate in the crossover. If `None`, the whole population is subject to the crossover. Returns: pl.DataFrame: the offspring resulting from the crossover. """ mating_pop = self.get_parents(population=population, to_mate=to_mate) mating_pop = mating_pop[self.variable_symbols].to_numpy().astype(float) num_var = mating_pop.shape[1] parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] n_pairs = parents1.shape[0] # One independent mask per mating pair. A single mask of shape (num_var,) would broadcast over # the whole mating pool, making every pair in the generation exchange exactly the same # variables -- a fixed column split rather than uniform crossover. swap = self.rng.random((n_pairs, num_var)) < self.uniform_xover_probability # The per-pair draw comes first and covers the whole row, so a pair that fails keeps its # variables together. Folding it into the per-variable rate would destroy that correlation, # which is the reason the two levels are separate. recombined = self.rng.random(n_pairs) <= self.pair_xover_probability swap &= recombined[:, np.newaxis] offspring1 = np.where(swap, parents2, parents1) offspring2 = np.where(swap, parents1, parents2) offspring = np.vstack((offspring1, offspring2)) # An odd sized mating pool was padded with a duplicate parent, so the last pair produced one # offspring too many. original_pop_size = len(to_mate) if to_mate is not None else population.shape[0] offspring = offspring[:original_pop_size] self.offspring_population = pl.from_numpy(offspring, schema=self.variable_symbols, orient="row") self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the uniform crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the uniform crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.uniform_xover_probability, ), ] # verbosity == 2 or higher return [ FloatMessage( topic=CrossoverMessageTopics.XOVER_PROBABILITY, source=self.__class__.__name__, value=self.uniform_xover_probability, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. The operator has no state that reacts to other components. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing. The operator has no state that reacts to other components.""" ``` #### UniformIntegerCrossover Bases: `BaseCrossover` A class that defines the uniform integer crossover operation. Each mating pair draws its own mask and every decision variable is inherited independently from one parent or the other, the two offspring taking complementary choices. This is the operator known as discrete crossover in the real-coded literature. References Syswerda, G. (1989). Uniform crossover in genetic algorithms. In Proceedings of the Third International Conference on Genetic Algorithms (pp. 2-9). Morgan Kaufmann. Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 Source code in `desdeo/emo/operators/crossover.py` ``` class UniformIntegerCrossover(BaseCrossover): """A class that defines the uniform integer crossover operation. Each mating pair draws its own mask and every decision variable is inherited independently from one parent or the other, the two offspring taking complementary choices. This is the operator known as discrete crossover in the real-coded literature. References: Syswerda, G. (1989). Uniform crossover in genetic algorithms. In Proceedings of the Third International Conference on Genetic Algorithms (pp. 2-9). Morgan Kaufmann. Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 """ def __init__(self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher): """Initialize the uniform integer crossover operator. Args: problem (Problem): the problem object. seed (int): the seed used in the random number generator for choosing the crossover point. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the single point binary crossover operator.""" return { 0: [], 1: [], 2: [ CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics the single point binary crossover operator is interested in.""" return [] def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform single point binary crossover. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None, optional): indices. Defaults to None. Returns: pl.DataFrame: the offspring from the crossover. """ self.parent_population = population pop_size = self.parent_population.shape[0] num_var = len(self.variable_symbols) parent_decision_vars = self.parent_population[self.variable_symbols].to_numpy().astype(int) if to_mate is None: shuffled_ids = list(range(pop_size)) self.rng.shuffle(shuffled_ids) else: shuffled_ids = copy.copy(to_mate) mating_pop = parent_decision_vars[shuffled_ids] mating_pop_size = len(shuffled_ids) original_mating_pop_size = mating_pop_size if mating_pop_size % 2 != 0: # if the number of member to mate is of uneven size, copy the first member to the tail mating_pop = np.vstack((mating_pop, mating_pop[0])) mating_pop_size += 1 shuffled_ids.append(shuffled_ids[0]) # split the population into parents, one with members with even numbered indices, the # other with uneven numbered indices parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] # One independent mask per mating pair. A single mask of shape (num_var,) would broadcast # over the whole mating pool, making every pair in the generation swap exactly the same # decision variables, which is a fixed column split rather than uniform crossover. mask = self.rng.choice([True, False], size=(mating_pop_size // 2, num_var)) offspring1 = np.where(mask, parents1, parents2) # True, pick from parent1, False, pick from parent2 offspring2 = np.where(mask, parents2, parents1) # True, pick from parent2, False, pick from parent1 # combine the two offspring populations into one, drop the last member if the number of # indices (to_mate) is uneven self.offspring_population = pl.from_numpy( np.vstack((offspring1, offspring2))[ : (original_mating_pop_size if original_mating_pop_size % 2 == 0 else -1) ], schema=self.variable_symbols, orient="row", ).select(pl.all().cast(pl.Float64)) self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing. This is just the basic single point binary crossover operator.""" def state(self) -> Sequence[Message]: """Return the state of the single ponit binary crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [] # verbosity == 2 or higher return [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics the single point binary crossover operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the single point binary crossover operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, ) ``` Initialize the uniform integer crossover operator. Parameters: | Name | Type | Description | Default | | ----------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `seed` | `int` | the seed used in the random number generator for choosing the crossover point. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__(self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher): """Initialize the uniform integer crossover operator. Args: problem (Problem): the problem object. seed (int): the seed used in the random number generator for choosing the crossover point. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform single point binary crossover. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | --------------------------------------------- | -------------------------- | | `population` | `DataFrame` | the population to perform the crossover with. | *required* | | `to_mate` | \`list[int] | None\` | indices. Defaults to None. | Returns: | Type | Description | | ----------- | ----------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform single point binary crossover. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None, optional): indices. Defaults to None. Returns: pl.DataFrame: the offspring from the crossover. """ self.parent_population = population pop_size = self.parent_population.shape[0] num_var = len(self.variable_symbols) parent_decision_vars = self.parent_population[self.variable_symbols].to_numpy().astype(int) if to_mate is None: shuffled_ids = list(range(pop_size)) self.rng.shuffle(shuffled_ids) else: shuffled_ids = copy.copy(to_mate) mating_pop = parent_decision_vars[shuffled_ids] mating_pop_size = len(shuffled_ids) original_mating_pop_size = mating_pop_size if mating_pop_size % 2 != 0: # if the number of member to mate is of uneven size, copy the first member to the tail mating_pop = np.vstack((mating_pop, mating_pop[0])) mating_pop_size += 1 shuffled_ids.append(shuffled_ids[0]) # split the population into parents, one with members with even numbered indices, the # other with uneven numbered indices parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] # One independent mask per mating pair. A single mask of shape (num_var,) would broadcast # over the whole mating pool, making every pair in the generation swap exactly the same # decision variables, which is a fixed column split rather than uniform crossover. mask = self.rng.choice([True, False], size=(mating_pop_size // 2, num_var)) offspring1 = np.where(mask, parents1, parents2) # True, pick from parent1, False, pick from parent2 offspring2 = np.where(mask, parents2, parents1) # True, pick from parent2, False, pick from parent1 # combine the two offspring populations into one, drop the last member if the number of # indices (to_mate) is uneven self.offspring_population = pl.from_numpy( np.vstack((offspring1, offspring2))[ : (original_mating_pop_size if original_mating_pop_size % 2 == 0 else -1) ], schema=self.variable_symbols, orient="row", ).select(pl.all().cast(pl.Float64)) self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the single ponit binary crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the single ponit binary crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [] # verbosity == 2 or higher return [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. This is just the basic single point binary crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing. This is just the basic single point binary crossover operator.""" ``` #### UniformMixedIntegerCrossover Bases: `BaseCrossover` A class that defines the uniform mixed-integer crossover operation. Each mating pair draws its own mask and every decision variable is inherited whole from one parent or the other, so integer valued variables keep integer values without any rounding. TODO: This is virtually identical to `UniformIntegerCrossover`. The only difference is that the `parent_decision_vars` in `do` are not casted to `int`. This is not an ideal way to implement crossover for mixed-integer stuff... References Syswerda, G. (1989). Uniform crossover in genetic algorithms. In Proceedings of the Third International Conference on Genetic Algorithms (pp. 2-9). Morgan Kaufmann. Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 Source code in `desdeo/emo/operators/crossover.py` ``` class UniformMixedIntegerCrossover(BaseCrossover): """A class that defines the uniform mixed-integer crossover operation. Each mating pair draws its own mask and every decision variable is inherited whole from one parent or the other, so integer valued variables keep integer values without any rounding. TODO: This is virtually identical to `UniformIntegerCrossover`. The only difference is that the `parent_decision_vars` in `do` are not casted to `int`. This is not an ideal way to implement crossover for mixed-integer stuff... References: Syswerda, G. (1989). Uniform crossover in genetic algorithms. In Proceedings of the Third International Conference on Genetic Algorithms (pp. 2-9). Morgan Kaufmann. Picek, S., Jakobovic, D., & Golub, M. (2013). On the recombination operator in the real-coded genetic algorithms. In 2013 IEEE Congress on Evolutionary Computation (pp. 3103-3110). https://doi.org/10.1109/CEC.2013.6557948 """ def __init__(self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher): """Initialize the uniform integer crossover operator. Args: problem (Problem): the problem object. seed (int): the seed used in the random number generator for choosing the crossover point. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) @property def provided_topics(self) -> dict[int, Sequence[CrossoverMessageTopics]]: """The message topics provided by the single point binary crossover operator.""" return { 0: [], 1: [], 2: [ CrossoverMessageTopics.PARENTS, CrossoverMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics the single point binary crossover operator is interested in.""" return [] def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform single point binary crossover. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None, optional): indices. Defaults to None. Returns: pl.DataFrame: the offspring from the crossover. """ self.parent_population = population pop_size = self.parent_population.shape[0] num_var = len(self.variable_symbols) parent_decision_vars = self.parent_population[self.variable_symbols].to_numpy().astype(float) if to_mate is None: shuffled_ids = list(range(pop_size)) self.rng.shuffle(shuffled_ids) else: shuffled_ids = copy.copy(to_mate) mating_pop = parent_decision_vars[shuffled_ids] mating_pop_size = len(shuffled_ids) original_mating_pop_size = mating_pop_size if mating_pop_size % 2 != 0: # if the number of member to mate is of uneven size, copy the first member to the tail mating_pop = np.vstack((mating_pop, mating_pop[0])) mating_pop_size += 1 shuffled_ids.append(shuffled_ids[0]) # split the population into parents, one with members with even numbered indices, the # other with uneven numbered indices parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] # One independent mask per mating pair. A single mask of shape (num_var,) would broadcast # over the whole mating pool, making every pair in the generation swap exactly the same # decision variables, which is a fixed column split rather than uniform crossover. mask = self.rng.choice([True, False], size=(mating_pop_size // 2, num_var)) offspring1 = np.where(mask, parents1, parents2) # True, pick from parent1, False, pick from parent2 offspring2 = np.where(mask, parents2, parents1) # True, pick from parent2, False, pick from parent1 # combine the two offspring populations into one, drop the last member if the number of # indices (to_mate) is uneven self.offspring_population = pl.from_numpy( np.vstack((offspring1, offspring2))[ : (original_mating_pop_size if original_mating_pop_size % 2 == 0 else -1) ], schema=self.variable_symbols, orient="row", ).select(pl.all().cast(pl.Float64)) self.notify() return self.offspring_population def update(self, *_, **__): """Do nothing. This is just the basic single point binary crossover operator.""" def state(self) -> Sequence[Message]: """Return the state of the single point binary crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [] # verbosity == 2 or higher return [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics the single point binary crossover operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[CrossoverMessageTopics]] ``` The message topics provided by the single point binary crossover operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, ) ``` Initialize the uniform integer crossover operator. Parameters: | Name | Type | Description | Default | | ----------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem object. | *required* | | `seed` | `int` | the seed used in the random number generator for choosing the crossover point. | *required* | | `verbosity` | `int` | the verbosity level of the component. The keys in provided_topics tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. | *required* | | `publisher` | `Publisher` | the publisher to which the operator will publish messages. | *required* | Source code in `desdeo/emo/operators/crossover.py` ``` def __init__(self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher): """Initialize the uniform integer crossover operator. Args: problem (Problem): the problem object. seed (int): the seed used in the random number generator for choosing the crossover point. verbosity (int): the verbosity level of the component. The keys in `provided_topics` tell what topics are provided by the operator at each verbosity level. Recommended to be set to 1. publisher (Publisher): the publisher to which the operator will publish messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) ``` ##### do ``` do( *, population: DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame ``` Perform single point binary crossover. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | --------------------------------------------- | -------------------------- | | `population` | `DataFrame` | the population to perform the crossover with. | *required* | | `to_mate` | \`list[int] | None\` | indices. Defaults to None. | Returns: | Type | Description | | ----------- | ----------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring from the crossover. | Source code in `desdeo/emo/operators/crossover.py` ``` def do( self, *, population: pl.DataFrame, to_mate: list[int] | None = None, ) -> pl.DataFrame: """Perform single point binary crossover. Args: population (pl.DataFrame): the population to perform the crossover with. to_mate (list[int] | None, optional): indices. Defaults to None. Returns: pl.DataFrame: the offspring from the crossover. """ self.parent_population = population pop_size = self.parent_population.shape[0] num_var = len(self.variable_symbols) parent_decision_vars = self.parent_population[self.variable_symbols].to_numpy().astype(float) if to_mate is None: shuffled_ids = list(range(pop_size)) self.rng.shuffle(shuffled_ids) else: shuffled_ids = copy.copy(to_mate) mating_pop = parent_decision_vars[shuffled_ids] mating_pop_size = len(shuffled_ids) original_mating_pop_size = mating_pop_size if mating_pop_size % 2 != 0: # if the number of member to mate is of uneven size, copy the first member to the tail mating_pop = np.vstack((mating_pop, mating_pop[0])) mating_pop_size += 1 shuffled_ids.append(shuffled_ids[0]) # split the population into parents, one with members with even numbered indices, the # other with uneven numbered indices parents1 = mating_pop[0::2, :] parents2 = mating_pop[1::2, :] # One independent mask per mating pair. A single mask of shape (num_var,) would broadcast # over the whole mating pool, making every pair in the generation swap exactly the same # decision variables, which is a fixed column split rather than uniform crossover. mask = self.rng.choice([True, False], size=(mating_pop_size // 2, num_var)) offspring1 = np.where(mask, parents1, parents2) # True, pick from parent1, False, pick from parent2 offspring2 = np.where(mask, parents2, parents1) # True, pick from parent2, False, pick from parent1 # combine the two offspring populations into one, drop the last member if the number of # indices (to_mate) is uneven self.offspring_population = pl.from_numpy( np.vstack((offspring1, offspring2))[ : (original_mating_pop_size if original_mating_pop_size % 2 == 0 else -1) ], schema=self.variable_symbols, orient="row", ).select(pl.all().cast(pl.Float64)) self.notify() return self.offspring_population ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the single point binary crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def state(self) -> Sequence[Message]: """Return the state of the single point binary crossover operator.""" if self.parent_population is None or self.offspring_population is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [] # verbosity == 2 or higher return [ PolarsDataFrameMessage( topic=CrossoverMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parent_population, ), PolarsDataFrameMessage( topic=CrossoverMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring_population, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. This is just the basic single point binary crossover operator. Source code in `desdeo/emo/operators/crossover.py` ``` def update(self, *_, **__): """Do nothing. This is just the basic single point binary crossover operator.""" ``` #### \_distinct_indices ``` _distinct_indices( rng: Generator, targets: ndarray, pop_size: int, k: int ) -> np.ndarray ``` Draw `k` indices per row, distinct from each other and from that row's target. Uses order-statistic shifting rather than rejection sampling: a value drawn from a range shortened by the number of already-excluded indices is shifted past each of them in sorted order, which lands uniformly on the admissible set in one pass. Rejection sampling would be simpler but its cost is data dependent, and a bounded retry loop that gives up leaves `r2 == r3` -- a zero difference vector, which silently turns differential evolution into a copy operator. Parameters: | Name | Type | Description | Default | | ---------- | ----------- | ---------------------------------------------- | ---------- | | `rng` | `Generator` | the generator to draw from. | *required* | | `targets` | `ndarray` | the index each row must avoid, shape (n,). | *required* | | `pop_size` | `int` | the size of the population being indexed into. | *required* | | `k` | `int` | how many distinct indices to draw per row. | *required* | Returns: | Type | Description | | --------- | ------------------------------------ | | `ndarray` | np.ndarray: indices of shape (n, k). | Source code in `desdeo/emo/operators/crossover.py` ``` def _distinct_indices(rng: np.random.Generator, targets: np.ndarray, pop_size: int, k: int) -> np.ndarray: """Draw `k` indices per row, distinct from each other and from that row's target. Uses order-statistic shifting rather than rejection sampling: a value drawn from a range shortened by the number of already-excluded indices is shifted past each of them in sorted order, which lands uniformly on the admissible set in one pass. Rejection sampling would be simpler but its cost is data dependent, and a bounded retry loop that gives up leaves `r2 == r3` -- a zero difference vector, which silently turns differential evolution into a copy operator. Args: rng: the generator to draw from. targets: the index each row must avoid, shape `(n,)`. pop_size: the size of the population being indexed into. k: how many distinct indices to draw per row. Returns: np.ndarray: indices of shape `(n, k)`. """ n = targets.shape[0] chosen = np.empty((n, k), dtype=np.int64) # Excluded indices per row, kept sorted so the shifts below apply in increasing order. excluded = targets[:, None].copy() for j in range(k): drawn = rng.integers(0, pop_size - (j + 1), size=n) for column in range(excluded.shape[1]): drawn += drawn >= excluded[:, column] chosen[:, j] = drawn excluded = np.sort(np.concatenate([excluded, drawn[:, None]], axis=1), axis=1) return chosen ``` ## Mutation operators ### desdeo.emo.operators.mutation Evolutionary operators for mutation. Various evolutionary operators for mutation in multiobjective optimization are defined here. #### BaseMutation Bases: `Subscriber` A base class for mutation operators. Source code in `desdeo/emo/operators/mutation.py` ``` class BaseMutation(Subscriber): """A base class for mutation operators.""" @abstractmethod def __init__(self, problem: Problem, verbosity: int, publisher: Publisher): """Initialize a mutation operator.""" super().__init__(verbosity=verbosity, publisher=publisher) self.problem = problem self.variable_symbols = [var.symbol for var in problem.get_flattened_variables()] self.lower_bounds = [var.lowerbound for var in problem.get_flattened_variables()] self.upper_bounds = [var.upperbound for var in problem.get_flattened_variables()] self.variable_types = [var.variable_type for var in problem.get_flattened_variables()] self.variable_combination: VariableDomainTypeEnum = problem.variable_domain # Populated by `do`. Initialized here so that `state` can be called before the first # mutation, e.g. by a logger that reports the operator's state up front. self.offspring_original: pl.DataFrame | None = None self.parents: pl.DataFrame | None = None self.offspring: pl.DataFrame | None = None @property def is_discrete(self) -> list[bool]: """Whether each (flattened) variable is restricted to integer values. Returns: list[bool]: one flag per variable, in the order of `variable_symbols`. """ return [var_type in (VariableTypeEnum.binary, VariableTypeEnum.integer) for var_type in self.variable_types] @abstractmethod def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Returns: pl.DataFrame: the offspring resulting from the mutation. """ ``` ##### is_discrete ``` is_discrete: list[bool] ``` Whether each (flattened) variable is restricted to integer values. Returns: | Type | Description | | ------------ | ---------------------------------------------------------------------- | | `list[bool]` | list\[bool\]: one flag per variable, in the order of variable_symbols. | ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher ) ``` Initialize a mutation operator. Source code in `desdeo/emo/operators/mutation.py` ``` @abstractmethod def __init__(self, problem: Problem, verbosity: int, publisher: Publisher): """Initialize a mutation operator.""" super().__init__(verbosity=verbosity, publisher=publisher) self.problem = problem self.variable_symbols = [var.symbol for var in problem.get_flattened_variables()] self.lower_bounds = [var.lowerbound for var in problem.get_flattened_variables()] self.upper_bounds = [var.upperbound for var in problem.get_flattened_variables()] self.variable_types = [var.variable_type for var in problem.get_flattened_variables()] self.variable_combination: VariableDomainTypeEnum = problem.variable_domain # Populated by `do`. Initialized here so that `state` can be called before the first # mutation, e.g. by a logger that reports the operator's state up front. self.offspring_original: pl.DataFrame | None = None self.parents: pl.DataFrame | None = None self.offspring: pl.DataFrame | None = None ``` ##### do ``` do( offsprings: DataFrame, parents: DataFrame ) -> pl.DataFrame ``` Perform the mutation operation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ----------------------------------------------------------------------------- | ---------- | | `offsprings` | `DataFrame` | the offspring population to mutate. | *required* | | `parents` | `DataFrame` | the parent population from which the offspring was generated (via crossover). | *required* | Returns: | Type | Description | | ----------- | -------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the mutation. | Source code in `desdeo/emo/operators/mutation.py` ``` @abstractmethod def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Returns: pl.DataFrame: the offspring resulting from the mutation. """ ``` #### BinaryFlipMutation Bases: `BaseMutation` Implements the bit flip mutation operator for binary variables. The binary flip mutation will mutate each binary decision variable, by flipping it (0 to 1, 1 to 0) with a provided probability. Source code in `desdeo/emo/operators/mutation.py` ``` class BinaryFlipMutation(BaseMutation): """Implements the bit flip mutation operator for binary variables. The binary flip mutation will mutate each binary decision variable, by flipping it (0 to 1, 1 to 0) with a provided probability. """ @property def provided_topics(self) -> dict[int, Sequence[MutationMessageTopics]]: """The message topics provided by the mutation operator.""" return { 0: [], 1: [ MutationMessageTopics.MUTATION_PROBABILITY, ], 2: [ MutationMessageTopics.MUTATION_PROBABILITY, MutationMessageTopics.OFFSPRING_ORIGINAL, MutationMessageTopics.PARENTS, MutationMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics that the mutation operator is interested in.""" return [] def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ): """Initialize a binary flip mutation operator. Args: problem (Problem): The problem object. seed (int): The seed for the random number generator. mutation_probability (float | None, optional): The probability of mutation. If None, the probability will be set to be 1/n, where n is the number of decision variables in the problem. Defaults to None. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if self.variable_combination != VariableDomainTypeEnum.binary: raise ValueError("This mutation operator only works with binary variables.") if mutation_probability is None: self.mutation_probability = 1 / len(self.variable_symbols) else: self.mutation_probability = mutation_probability self.rng = np.random.default_rng(seed) self.seed = seed def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the binary flip mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. Returns: pl.DataFrame: the offspring resulting from the mutation. """ self.offspring_original = copy.copy(offsprings) self.parents = parents # Not used, but kept for consistency offspring = offsprings.to_numpy(writable=True).astype(dtype=np.bool) # create a boolean mask based on the mutation probability flip_mask = self.rng.random(offspring.shape) < self.mutation_probability # using XOR (^), flip the bits in the offspring when the mask is True # otherwise leave the bit's value as it is offspring = offspring ^ flip_mask self.offspring = ( pl.from_numpy(offspring, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics that the mutation operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[MutationMessageTopics]] ``` The message topics provided by the mutation operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ) ``` Initialize a binary flip mutation operator. Parameters: | Name | Type | Description | Default | | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | The problem object. | *required* | | `seed` | `int` | The seed for the random number generator. | *required* | | `mutation_probability` | \`float | None\` | The probability of mutation. If None, the probability will be set to be 1/n, where n is the number of decision variables in the problem. Defaults to None. | | `verbosity` | `int` | The verbosity level of the operator. See the provided_topics attribute to see what messages are provided at each verbosity level. Recommended value is 1. | *required* | | `publisher` | `Publisher` | The publisher to which the operator will send messages. | *required* | Source code in `desdeo/emo/operators/mutation.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ): """Initialize a binary flip mutation operator. Args: problem (Problem): The problem object. seed (int): The seed for the random number generator. mutation_probability (float | None, optional): The probability of mutation. If None, the probability will be set to be 1/n, where n is the number of decision variables in the problem. Defaults to None. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if self.variable_combination != VariableDomainTypeEnum.binary: raise ValueError("This mutation operator only works with binary variables.") if mutation_probability is None: self.mutation_probability = 1 / len(self.variable_symbols) else: self.mutation_probability = mutation_probability self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do( offsprings: DataFrame, parents: DataFrame ) -> pl.DataFrame ``` Perform the binary flip mutation operation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ---------------------------------------------------------------------------------------------------------------- | ---------- | | `offsprings` | `DataFrame` | the offspring population to mutate. | *required* | | `parents` | `DataFrame` | the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. | *required* | Returns: | Type | Description | | ----------- | -------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the mutation. | Source code in `desdeo/emo/operators/mutation.py` ``` def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the binary flip mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. Returns: pl.DataFrame: the offspring resulting from the mutation. """ self.offspring_original = copy.copy(offsprings) self.parents = parents # Not used, but kept for consistency offspring = offsprings.to_numpy(writable=True).astype(dtype=np.bool) # create a boolean mask based on the mutation probability flip_mask = self.rng.random(offspring.shape) < self.mutation_probability # using XOR (^), flip the bits in the offspring when the mask is True # otherwise leave the bit's value as it is offspring = offspring ^ flip_mask self.offspring = ( pl.from_numpy(offspring, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the mutation operator. Source code in `desdeo/emo/operators/mutation.py` ``` def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/mutation.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### BoundedPolynomialMutation Bases: `BaseMutation` Implements the bounded polynomial mutation operator. Reference Deb, K., & Goyal, M. (1996). A combined genetic adaptive search (GeneAS) for engineering design. Computer Science and informatics, 26(4), 30-45, 1996. Source code in `desdeo/emo/operators/mutation.py` ``` class BoundedPolynomialMutation(BaseMutation): """Implements the bounded polynomial mutation operator. Reference: Deb, K., & Goyal, M. (1996). A combined genetic adaptive search (GeneAS) for engineering design. Computer Science and informatics, 26(4), 30-45, 1996. """ @property def provided_topics(self) -> dict[int, Sequence[MutationMessageTopics]]: """The message topics provided by the mutation operator.""" return { 0: [], 1: [ MutationMessageTopics.MUTATION_PROBABILITY, MutationMessageTopics.MUTATION_DISTRIBUTION, ], 2: [ MutationMessageTopics.MUTATION_PROBABILITY, MutationMessageTopics.MUTATION_DISTRIBUTION, MutationMessageTopics.OFFSPRING_ORIGINAL, MutationMessageTopics.PARENTS, MutationMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics that the mutation operator is interested in.""" return [] def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, distribution_index: float = 20, ): """Initialize a bounded polynomial mutation operator. Args: problem (Problem): The problem object. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. mutation_probability (float | None, optional): The probability of mutation. Defaults to None. distribution_index (float, optional): The distribution index for polynomial mutation. Defaults to 20. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if self.variable_combination != VariableDomainTypeEnum.continuous: raise ValueError("This mutation operator only works with continuous variables.") if mutation_probability is None: self.mutation_probability = 1 / len(self.lower_bounds) else: self.mutation_probability = mutation_probability self.distribution_index = distribution_index self.rng = np.random.default_rng(seed) self.seed = seed def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Returns: pl.DataFrame: the offspring resulting from the mutation. """ # TODO(@light-weaver): Extract to a numba jitted function self.offspring_original = offsprings self.parents = parents # Not used, but kept for consistency # Note: `to_numpy` hands back an F-contiguous array. Every `pl.from_numpy` in this module # therefore states `orient="row"`: for a square population (as many individuals as # variables) polars cannot infer the orientation from the shape, and would read such an # array column-wise, transposing the population. offspring = offsprings.to_numpy(writable=True) min_val = np.ones_like(offspring) * self.lower_bounds max_val = np.ones_like(offspring) * self.upper_bounds k = self.rng.random(size=offspring.shape) miu = self.rng.random(size=offspring.shape) # A fixed variable has a single feasible value, and scaling by the width of an empty # interval would divide by zero. The resulting nan would survive the clipping below, # because every comparison against nan is False, so leave those genes alone instead. mutatable = np.logical_and(k <= self.mutation_probability, max_val > min_val) temp = np.logical_and(mutatable, (miu < 0.5)) # noqa: PLR2004 # The polynomial mutation formula can still raise negative scaled values to fractional # powers; the offspring are clipped to the bounds afterwards, so the intermediate inf is # discarded. Silence the resulting benign numpy warnings. with np.errstate(divide="ignore", over="ignore", invalid="ignore"): offspring_scaled = (offspring - min_val) / (max_val - min_val) offspring[temp] = offspring[temp] + ( (max_val[temp] - min_val[temp]) * ( ( 2 * miu[temp] + (1 - 2 * miu[temp]) * (1 - offspring_scaled[temp]) ** (self.distribution_index + 1) ) ** (1 / (self.distribution_index + 1)) - 1 ) ) temp = np.logical_and(mutatable, (miu >= 0.5)) # noqa: PLR2004 offspring[temp] = offspring[temp] + ( (max_val[temp] - min_val[temp]) * ( 1 - ( 2 * (1 - miu[temp]) + 2 * (miu[temp] - 0.5) * offspring_scaled[temp] ** (self.distribution_index + 1) ) ** (1 / (self.distribution_index + 1)) ) ) offspring[offspring > max_val] = max_val[offspring > max_val] offspring[offspring < min_val] = min_val[offspring < min_val] self.offspring = pl.from_numpy(offspring, schema=self.variable_symbols, orient="row") self.notify() return self.offspring def update(self, *_, **__): """Do nothing. This is just the basic polynomial mutation operator.""" def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), FloatMessage( topic=MutationMessageTopics.MUTATION_DISTRIBUTION, source=self.__class__.__name__, value=self.distribution_index, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), FloatMessage( topic=MutationMessageTopics.MUTATION_DISTRIBUTION, source=self.__class__.__name__, value=self.distribution_index, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics that the mutation operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[MutationMessageTopics]] ``` The message topics provided by the mutation operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, distribution_index: float = 20, ) ``` Initialize a bounded polynomial mutation operator. Parameters: | Name | Type | Description | Default | | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | | `problem` | `Problem` | The problem object. | *required* | | `seed` | `int` | The seed for the random number generator. | *required* | | `verbosity` | `int` | The verbosity level of the operator. See the provided_topics attribute to see what messages are provided at each verbosity level. Recommended value is 1. | *required* | | `publisher` | `Publisher` | The publisher to which the operator will send messages. | *required* | | `mutation_probability` | \`float | None\` | The probability of mutation. Defaults to None. | | `distribution_index` | `float` | The distribution index for polynomial mutation. Defaults to 20. | `20` | Source code in `desdeo/emo/operators/mutation.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, distribution_index: float = 20, ): """Initialize a bounded polynomial mutation operator. Args: problem (Problem): The problem object. seed (int): The seed for the random number generator. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. mutation_probability (float | None, optional): The probability of mutation. Defaults to None. distribution_index (float, optional): The distribution index for polynomial mutation. Defaults to 20. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if self.variable_combination != VariableDomainTypeEnum.continuous: raise ValueError("This mutation operator only works with continuous variables.") if mutation_probability is None: self.mutation_probability = 1 / len(self.lower_bounds) else: self.mutation_probability = mutation_probability self.distribution_index = distribution_index self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do( offsprings: DataFrame, parents: DataFrame ) -> pl.DataFrame ``` Perform the mutation operation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ----------------------------------------------------------------------------- | ---------- | | `offsprings` | `DataFrame` | the offspring population to mutate. | *required* | | `parents` | `DataFrame` | the parent population from which the offspring was generated (via crossover). | *required* | Returns: | Type | Description | | ----------- | -------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the mutation. | Source code in `desdeo/emo/operators/mutation.py` ``` def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Returns: pl.DataFrame: the offspring resulting from the mutation. """ # TODO(@light-weaver): Extract to a numba jitted function self.offspring_original = offsprings self.parents = parents # Not used, but kept for consistency # Note: `to_numpy` hands back an F-contiguous array. Every `pl.from_numpy` in this module # therefore states `orient="row"`: for a square population (as many individuals as # variables) polars cannot infer the orientation from the shape, and would read such an # array column-wise, transposing the population. offspring = offsprings.to_numpy(writable=True) min_val = np.ones_like(offspring) * self.lower_bounds max_val = np.ones_like(offspring) * self.upper_bounds k = self.rng.random(size=offspring.shape) miu = self.rng.random(size=offspring.shape) # A fixed variable has a single feasible value, and scaling by the width of an empty # interval would divide by zero. The resulting nan would survive the clipping below, # because every comparison against nan is False, so leave those genes alone instead. mutatable = np.logical_and(k <= self.mutation_probability, max_val > min_val) temp = np.logical_and(mutatable, (miu < 0.5)) # noqa: PLR2004 # The polynomial mutation formula can still raise negative scaled values to fractional # powers; the offspring are clipped to the bounds afterwards, so the intermediate inf is # discarded. Silence the resulting benign numpy warnings. with np.errstate(divide="ignore", over="ignore", invalid="ignore"): offspring_scaled = (offspring - min_val) / (max_val - min_val) offspring[temp] = offspring[temp] + ( (max_val[temp] - min_val[temp]) * ( ( 2 * miu[temp] + (1 - 2 * miu[temp]) * (1 - offspring_scaled[temp]) ** (self.distribution_index + 1) ) ** (1 / (self.distribution_index + 1)) - 1 ) ) temp = np.logical_and(mutatable, (miu >= 0.5)) # noqa: PLR2004 offspring[temp] = offspring[temp] + ( (max_val[temp] - min_val[temp]) * ( 1 - ( 2 * (1 - miu[temp]) + 2 * (miu[temp] - 0.5) * offspring_scaled[temp] ** (self.distribution_index + 1) ) ** (1 / (self.distribution_index + 1)) ) ) offspring[offspring > max_val] = max_val[offspring > max_val] offspring[offspring < min_val] = min_val[offspring < min_val] self.offspring = pl.from_numpy(offspring, schema=self.variable_symbols, orient="row") self.notify() return self.offspring ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the mutation operator. Source code in `desdeo/emo/operators/mutation.py` ``` def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), FloatMessage( topic=MutationMessageTopics.MUTATION_DISTRIBUTION, source=self.__class__.__name__, value=self.distribution_index, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), FloatMessage( topic=MutationMessageTopics.MUTATION_DISTRIBUTION, source=self.__class__.__name__, value=self.distribution_index, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. This is just the basic polynomial mutation operator. Source code in `desdeo/emo/operators/mutation.py` ``` def update(self, *_, **__): """Do nothing. This is just the basic polynomial mutation operator.""" ``` #### IntegerRandomMutation Bases: `BaseMutation` Implements a random mutation operator for integer variables. The mutation will mutate each binary integer variable, by changing its value to a random value bounded by the variable's bounds with a provided probability. Source code in `desdeo/emo/operators/mutation.py` ``` class IntegerRandomMutation(BaseMutation): """Implements a random mutation operator for integer variables. The mutation will mutate each binary integer variable, by changing its value to a random value bounded by the variable's bounds with a provided probability. """ @property def provided_topics(self) -> dict[int, Sequence[MutationMessageTopics]]: """The message topics provided by the mutation operator.""" return { 0: [], 1: [ MutationMessageTopics.MUTATION_PROBABILITY, ], 2: [ MutationMessageTopics.MUTATION_PROBABILITY, MutationMessageTopics.OFFSPRING_ORIGINAL, MutationMessageTopics.PARENTS, MutationMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics that the mutation operator is interested in.""" return [] def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ): """Initialize a random integer mutation operator. Args: problem (Problem): The problem object. seed (int): The seed for the random number generator. mutation_probability (float | None, optional): The probability of mutation. If None, the probability will be set to be 1/n, where n is the number of decision variables in the problem. Defaults to None. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if self.variable_combination != VariableDomainTypeEnum.integer: raise ValueError("This mutation operator only works with integer variables.") if mutation_probability is None: self.mutation_probability = 1 / len(self.variable_symbols) else: self.mutation_probability = mutation_probability self.rng = np.random.default_rng(seed) self.seed = seed def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the random integer mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. Returns: pl.DataFrame: the offspring resulting from the mutation. """ self.offspring_original = copy.copy(offsprings) self.parents = parents # Not used, but kept for consistency population = offsprings.to_numpy(writable=True).astype(int) # create a boolean mask based on the mutation probability mutation_mask = self.rng.random(population.shape) < self.mutation_probability mutated = np.where( mutation_mask, self.rng.integers(self.lower_bounds, self.upper_bounds, size=population.shape, dtype=int, endpoint=True), population, ) self.offspring = ( pl.from_numpy(mutated, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics that the mutation operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[MutationMessageTopics]] ``` The message topics provided by the mutation operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ) ``` Initialize a random integer mutation operator. Parameters: | Name | Type | Description | Default | | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | The problem object. | *required* | | `seed` | `int` | The seed for the random number generator. | *required* | | `mutation_probability` | \`float | None\` | The probability of mutation. If None, the probability will be set to be 1/n, where n is the number of decision variables in the problem. Defaults to None. | | `verbosity` | `int` | The verbosity level of the operator. See the provided_topics attribute to see what messages are provided at each verbosity level. Recommended value is 1. | *required* | | `publisher` | `Publisher` | The publisher to which the operator will send messages. | *required* | Source code in `desdeo/emo/operators/mutation.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ): """Initialize a random integer mutation operator. Args: problem (Problem): The problem object. seed (int): The seed for the random number generator. mutation_probability (float | None, optional): The probability of mutation. If None, the probability will be set to be 1/n, where n is the number of decision variables in the problem. Defaults to None. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if self.variable_combination != VariableDomainTypeEnum.integer: raise ValueError("This mutation operator only works with integer variables.") if mutation_probability is None: self.mutation_probability = 1 / len(self.variable_symbols) else: self.mutation_probability = mutation_probability self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do( offsprings: DataFrame, parents: DataFrame ) -> pl.DataFrame ``` Perform the random integer mutation operation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ---------------------------------------------------------------------------------------------------------------- | ---------- | | `offsprings` | `DataFrame` | the offspring population to mutate. | *required* | | `parents` | `DataFrame` | the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. | *required* | Returns: | Type | Description | | ----------- | -------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the mutation. | Source code in `desdeo/emo/operators/mutation.py` ``` def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the random integer mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. Returns: pl.DataFrame: the offspring resulting from the mutation. """ self.offspring_original = copy.copy(offsprings) self.parents = parents # Not used, but kept for consistency population = offsprings.to_numpy(writable=True).astype(int) # create a boolean mask based on the mutation probability mutation_mask = self.rng.random(population.shape) < self.mutation_probability mutated = np.where( mutation_mask, self.rng.integers(self.lower_bounds, self.upper_bounds, size=population.shape, dtype=int, endpoint=True), population, ) self.offspring = ( pl.from_numpy(mutated, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the mutation operator. Source code in `desdeo/emo/operators/mutation.py` ``` def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/mutation.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### MPTMutation Bases: `BaseMutation` Makinen, Periaux and Toivanen (MTP) mutation. Applies small mutations to mixed-integer variables using a mutation exponent strategy. Source code in `desdeo/emo/operators/mutation.py` ``` class MPTMutation(BaseMutation): """Makinen, Periaux and Toivanen (MTP) mutation. Applies small mutations to mixed-integer variables using a mutation exponent strategy. """ @property def provided_topics(self) -> dict[int, Sequence[MutationMessageTopics]]: """The message topics provided by the mutation operator.""" return { 0: [], 1: [MutationMessageTopics.MUTATION_PROBABILITY], 2: [ MutationMessageTopics.MUTATION_PROBABILITY, MutationMessageTopics.OFFSPRING_ORIGINAL, MutationMessageTopics.PARENTS, MutationMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics that the mutation operator is interested in.""" return [] def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, mutation_exponent: float = 2.0, ): """Initialize a small mutation operator. Args: problem (Problem): Optimization problem. seed (int): RNG seed. mutation_probability (float | None): Probability of mutation per gene. mutation_exponent (float): Controls strength of small mutation (larger means smaller mutations). verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. publisher must be passed. See the Subscriber class for more information. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.rng = np.random.default_rng(seed) self.seed = seed self.mutation_exponent = mutation_exponent self.mutation_probability = ( 1 / len(self.variable_symbols) if mutation_probability is None else mutation_probability ) def _mutate_value(self, x, lower_bound, upper_bound): """Apply small mutation to a single float value using mutation exponent.""" if upper_bound == lower_bound: # A fixed variable has a single feasible value; scaling by the width would divide by zero. return lower_bound t = (x - lower_bound) / (upper_bound - lower_bound) rnd = self.rng.uniform(0, 1) if rnd < t: tm = t - t * ((t - rnd) / t) ** self.mutation_exponent elif rnd > t: tm = t + (1 - t) * ((rnd - t) / (1 - t)) ** self.mutation_exponent else: tm = t return (1 - tm) * lower_bound + tm * upper_bound def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the MPT mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. Returns: pl.DataFrame: the offspring resulting from the mutation. """ self.offspring_original = copy.copy(offsprings) self.parents = parents population = offsprings.to_numpy(writable=True).astype(float) bounds = list(zip(self.lower_bounds, self.upper_bounds, self.is_discrete, strict=True)) for i in range(population.shape[0]): for j, (lower_bound, upper_bound, discrete) in enumerate(bounds): if self.rng.random() < self.mutation_probability: mutated = self._mutate_value(population[i, j], lower_bound, upper_bound) # Round after float mutation to keep integer domain. `np.round` rather than # `round`, which raises on the NaN some crossover operators produce. population[i, j] = np.round(mutated) if discrete else mutated self.offspring = ( pl.from_numpy(population, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics that the mutation operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[MutationMessageTopics]] ``` The message topics provided by the mutation operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, mutation_exponent: float = 2.0, ) ``` Initialize a small mutation operator. Parameters: | Name | Type | Description | Default | | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- | | `problem` | `Problem` | Optimization problem. | *required* | | `seed` | `int` | RNG seed. | *required* | | `mutation_probability` | \`float | None\` | Probability of mutation per gene. | | `mutation_exponent` | `float` | Controls strength of small mutation (larger means smaller mutations). | `2.0` | | `verbosity` | `int` | The verbosity level of the operator. See the provided_topics attribute to see what messages are provided at each verbosity level. Recommended value is 1. | *required* | | `publisher` | `Publisher` | The publisher to which the operator will send messages. publisher must be passed. See the Subscriber class for more information. | *required* | Source code in `desdeo/emo/operators/mutation.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, mutation_exponent: float = 2.0, ): """Initialize a small mutation operator. Args: problem (Problem): Optimization problem. seed (int): RNG seed. mutation_probability (float | None): Probability of mutation per gene. mutation_exponent (float): Controls strength of small mutation (larger means smaller mutations). verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. publisher must be passed. See the Subscriber class for more information. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.rng = np.random.default_rng(seed) self.seed = seed self.mutation_exponent = mutation_exponent self.mutation_probability = ( 1 / len(self.variable_symbols) if mutation_probability is None else mutation_probability ) ``` ##### \_mutate_value ``` _mutate_value(x, lower_bound, upper_bound) ``` Apply small mutation to a single float value using mutation exponent. Source code in `desdeo/emo/operators/mutation.py` ``` def _mutate_value(self, x, lower_bound, upper_bound): """Apply small mutation to a single float value using mutation exponent.""" if upper_bound == lower_bound: # A fixed variable has a single feasible value; scaling by the width would divide by zero. return lower_bound t = (x - lower_bound) / (upper_bound - lower_bound) rnd = self.rng.uniform(0, 1) if rnd < t: tm = t - t * ((t - rnd) / t) ** self.mutation_exponent elif rnd > t: tm = t + (1 - t) * ((rnd - t) / (1 - t)) ** self.mutation_exponent else: tm = t return (1 - tm) * lower_bound + tm * upper_bound ``` ##### do ``` do( offsprings: DataFrame, parents: DataFrame ) -> pl.DataFrame ``` Perform the MPT mutation operation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ---------------------------------------------------------------------------------------------------------------- | ---------- | | `offsprings` | `DataFrame` | the offspring population to mutate. | *required* | | `parents` | `DataFrame` | the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. | *required* | Returns: | Type | Description | | ----------- | -------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the mutation. | Source code in `desdeo/emo/operators/mutation.py` ``` def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the MPT mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. Returns: pl.DataFrame: the offspring resulting from the mutation. """ self.offspring_original = copy.copy(offsprings) self.parents = parents population = offsprings.to_numpy(writable=True).astype(float) bounds = list(zip(self.lower_bounds, self.upper_bounds, self.is_discrete, strict=True)) for i in range(population.shape[0]): for j, (lower_bound, upper_bound, discrete) in enumerate(bounds): if self.rng.random() < self.mutation_probability: mutated = self._mutate_value(population[i, j], lower_bound, upper_bound) # Round after float mutation to keep integer domain. `np.round` rather than # `round`, which raises on the NaN some crossover operators produce. population[i, j] = np.round(mutated) if discrete else mutated self.offspring = ( pl.from_numpy(population, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the mutation operator. Source code in `desdeo/emo/operators/mutation.py` ``` def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/mutation.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### MixedIntegerRandomMutation Bases: `BaseMutation` Implements a random mutation operator for mixed-integer variables. The mutation will mutate each mixed-integer variable, by changing its value to a random value bounded by the variable's bounds with a provided probability. Source code in `desdeo/emo/operators/mutation.py` ``` class MixedIntegerRandomMutation(BaseMutation): """Implements a random mutation operator for mixed-integer variables. The mutation will mutate each mixed-integer variable, by changing its value to a random value bounded by the variable's bounds with a provided probability. """ @property def provided_topics(self) -> dict[int, Sequence[MutationMessageTopics]]: """The message topics provided by the mutation operator.""" return { 0: [], 1: [ MutationMessageTopics.MUTATION_PROBABILITY, ], 2: [ MutationMessageTopics.MUTATION_PROBABILITY, MutationMessageTopics.OFFSPRING_ORIGINAL, MutationMessageTopics.PARENTS, MutationMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics that the mutation operator is interested in.""" return [] def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ): """Initialize a random mixed_integer mutation operator. Args: problem (Problem): The problem object. seed (int): The seed for the random number generator. mutation_probability (float | None, optional): The probability of mutation. If None, the probability will be set to be 1/n, where n is the number of decision variables in the problem. Defaults to None. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if mutation_probability is None: self.mutation_probability = 1 / len(self.variable_symbols) else: self.mutation_probability = mutation_probability self.rng = np.random.default_rng(seed) self.seed = seed def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the random integer mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. Returns: pl.DataFrame: the offspring resulting from the mutation. """ self.offspring_original = copy.copy(offsprings) self.parents = parents # Not used, but kept for consistency population = offsprings.to_numpy(writable=True).astype(float) # create a boolean mask based on the mutation probability mutation_mask = self.rng.random(population.shape) < self.mutation_probability mutation_pool = np.array( [ self.rng.integers(low=int(lower), high=int(upper), size=population.shape[0], endpoint=True).astype( dtype=float ) if discrete else self.rng.uniform(low=lower, high=upper, size=population.shape[0]).astype(dtype=float) for lower, upper, discrete in zip(self.lower_bounds, self.upper_bounds, self.is_discrete, strict=True) ] ).T mutated = np.where( mutation_mask, # self.rng.integers(self.lower_bounds, self.upper_bounds, size=population.shape, dtype=int, endpoint=True), mutation_pool, population, ) self.offspring = ( pl.from_numpy(mutated, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics that the mutation operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[MutationMessageTopics]] ``` The message topics provided by the mutation operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ) ``` Initialize a random mixed_integer mutation operator. Parameters: | Name | Type | Description | Default | | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | The problem object. | *required* | | `seed` | `int` | The seed for the random number generator. | *required* | | `mutation_probability` | \`float | None\` | The probability of mutation. If None, the probability will be set to be 1/n, where n is the number of decision variables in the problem. Defaults to None. | | `verbosity` | `int` | The verbosity level of the operator. See the provided_topics attribute to see what messages are provided at each verbosity level. Recommended value is 1. | *required* | | `publisher` | `Publisher` | The publisher to which the operator will send messages. | *required* | Source code in `desdeo/emo/operators/mutation.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ): """Initialize a random mixed_integer mutation operator. Args: problem (Problem): The problem object. seed (int): The seed for the random number generator. mutation_probability (float | None, optional): The probability of mutation. If None, the probability will be set to be 1/n, where n is the number of decision variables in the problem. Defaults to None. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if mutation_probability is None: self.mutation_probability = 1 / len(self.variable_symbols) else: self.mutation_probability = mutation_probability self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do( offsprings: DataFrame, parents: DataFrame ) -> pl.DataFrame ``` Perform the random integer mutation operation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ---------------------------------------------------------------------------------------------------------------- | ---------- | | `offsprings` | `DataFrame` | the offspring population to mutate. | *required* | | `parents` | `DataFrame` | the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. | *required* | Returns: | Type | Description | | ----------- | -------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the offspring resulting from the mutation. | Source code in `desdeo/emo/operators/mutation.py` ``` def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform the random integer mutation operation. Args: offsprings (pl.DataFrame): the offspring population to mutate. parents (pl.DataFrame): the parent population from which the offspring was generated (via crossover). Not used in the mutation operator. Returns: pl.DataFrame: the offspring resulting from the mutation. """ self.offspring_original = copy.copy(offsprings) self.parents = parents # Not used, but kept for consistency population = offsprings.to_numpy(writable=True).astype(float) # create a boolean mask based on the mutation probability mutation_mask = self.rng.random(population.shape) < self.mutation_probability mutation_pool = np.array( [ self.rng.integers(low=int(lower), high=int(upper), size=population.shape[0], endpoint=True).astype( dtype=float ) if discrete else self.rng.uniform(low=lower, high=upper, size=population.shape[0]).astype(dtype=float) for lower, upper, discrete in zip(self.lower_bounds, self.upper_bounds, self.is_discrete, strict=True) ] ).T mutated = np.where( mutation_mask, # self.rng.integers(self.lower_bounds, self.upper_bounds, size=population.shape, dtype=int, endpoint=True), mutation_pool, population, ) self.offspring = ( pl.from_numpy(mutated, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the mutation operator. Source code in `desdeo/emo/operators/mutation.py` ``` def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/mutation.py` ``` def update(self, *_, **__): """Do nothing.""" ``` #### NonUniformMutation Bases: `BaseMutation` Non-uniform mutation operator. The mutation strength decays over generations. The decay is driven by how far the run has progressed towards its budget. The budget is taken from the terminator's messages, so the operator stays in step with the terminator even when the number of generations is not known in advance (for example when the run is terminated by a maximum number of function evaluations). A budget passed explicitly via `max_generations` takes precedence over the messages. Source code in `desdeo/emo/operators/mutation.py` ``` class NonUniformMutation(BaseMutation): """Non-uniform mutation operator. The mutation strength decays over generations. The decay is driven by how far the run has progressed towards its budget. The budget is taken from the terminator's messages, so the operator stays in step with the terminator even when the number of generations is not known in advance (for example when the run is terminated by a maximum number of function evaluations). A budget passed explicitly via `max_generations` takes precedence over the messages. """ @property def provided_topics(self) -> dict[int, Sequence[MutationMessageTopics]]: """The message topics provided by the mutation operator.""" return { 0: [], 1: [MutationMessageTopics.MUTATION_PROBABILITY], 2: [ MutationMessageTopics.MUTATION_PROBABILITY, MutationMessageTopics.OFFSPRING_ORIGINAL, MutationMessageTopics.PARENTS, MutationMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics that the mutation operator is interested in.""" return [ TerminatorMessageTopics.GENERATION, TerminatorMessageTopics.MAX_GENERATIONS, TerminatorMessageTopics.EVALUATION, TerminatorMessageTopics.MAX_EVALUATIONS, ] def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, max_generations: int | None = None, mutation_probability: float | None = None, b: float = 5.0, # decay parameter ): """Initialize a Non-uniform mutation operator. Args: problem (Problem): The optimization problem definition. seed (int): Random number generator seed for reproducibility. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. max_generations (int | None): Maximum number of generations in the evolutionary run, used to scale mutation decay. Defaults to None, in which case the budget reported by the terminator is used, falling back to the number of function evaluations if the terminator does not bound the number of generations. Prefer leaving this as None: a value that disagrees with the terminator makes the decay schedule finish too early or not at all. mutation_probability (float | None): Probability of mutating each gene. If None, defaults to 1 / number of variables. b (float): Non-uniform mutation decay parameter. Higher values cause faster reduction in mutation strength over generations. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if max_generations is not None and max_generations <= 0: raise ValueError(f"max_generations must be a positive integer, got {max_generations}.") self.rng = np.random.default_rng(seed) self.seed = seed self.b = b self.current_generation = 0 self.max_generations = max_generations self.current_evaluations = 0 self.max_evaluations: int | None = None # Budget reported by the terminator, used when max_generations was not given explicitly. self.reported_max_generations: int | None = None self._warned_past_budget = False self.mutation_probability = ( 1 / len(self.variable_symbols) if mutation_probability is None else mutation_probability ) @property def decay_progress(self) -> float: """The fraction of the run that has elapsed, in [0, 1]. A value of 0 means full mutation strength and a value of 1 means no mutation at all. The ratio must never leave [0, 1]: a negative `1 - progress` would be raised to the power `b` below, which yields a complex number for a fractional `b` and overflows the float range for an integral one. Returns: float: the elapsed fraction of the run, clamped to [0, 1]. Zero if no budget is known. """ max_generations = self.max_generations if self.max_generations is not None else self.reported_max_generations if max_generations is not None and max_generations > 0: progress = self.current_generation / max_generations if progress > 1.0 and self.max_generations is not None and not self._warned_past_budget: self._warned_past_budget = True warnings.warn( f"{self.__class__.__name__} was given max_generations={self.max_generations}, but the run has " f"reached generation {self.current_generation}. The mutation strength has already decayed to " "zero and stays there for the rest of the run. Leave max_generations as None to let the " "operator follow the terminator's budget instead.", stacklevel=2, ) return min(progress, 1.0) if self.max_evaluations is not None and self.max_evaluations > 0: return min(self.current_evaluations / self.max_evaluations, 1.0) # Nothing bounds the run (e.g. a time based terminator), so keep the mutation at full strength. return 0.0 def _mutate_value(self, x: float, lower_bound: float, upper_bound: float, mutation_threshold: float = 0.5) -> float: """Apply non-uniform mutation to a single float value. Args: x (float): The current value of the gene to be mutated. lower_bound (float): The lower bound of the gene. upper_bound (float): The upper bound of the gene. mutation_threshold (float): The mutation threshold. Defaults to 0.5. Returns: float: The mutated gene value, clipped within the bounds [l, u]. """ r = self.rng.uniform(0, 1) # Random number to choose direction b = self.b u_rand = self.rng.uniform(0, 1) # Random number for mutation strength tau = (1 - self.decay_progress) ** b if r <= mutation_threshold: y = upper_bound - x delta = y * (1 - u_rand**tau) xm = x + delta else: y = x - lower_bound delta = y * (1 - u_rand**tau) xm = x - delta return np.clip(xm, lower_bound, upper_bound) def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform non-uniform mutation. Args: offsprings (pl.DataFrame): The current offspring population to mutate. Each row corresponds to one individual. parents (pl.DataFrame): The parent population (not used in mutation but passed for interface consistency). Returns: pl.DataFrame: A new offspring population with mutated values applied. Returned as a Polars DataFrame. """ self.offspring_original = copy.copy(offsprings) self.parents = parents population = offsprings.to_numpy(writable=True).astype(float) bounds = list(zip(self.lower_bounds, self.upper_bounds, self.is_discrete, strict=True)) for i in range(population.shape[0]): for j, (lower_bound, upper_bound, discrete) in enumerate(bounds): if self.rng.random() < self.mutation_probability: mutated = self._mutate_value(population[i, j], lower_bound, upper_bound) # Round to keep the integer domain. `np.round` rather than `round`, which # raises on the NaN some crossover operators produce. population[i, j] = np.round(mutated) if discrete else mutated self.offspring = pl.from_numpy(population, schema=self.variable_symbols, orient="row").cast(pl.Float64) self.notify() return self.offspring def update(self, message: Message): """Track the progress of the run (used to reduce mutation strength over time).""" if not isinstance(message.topic, TerminatorMessageTopics): return if not isinstance(message.value, int): return match message.topic: case TerminatorMessageTopics.GENERATION: self.current_generation = message.value case TerminatorMessageTopics.MAX_GENERATIONS: self.reported_max_generations = message.value case TerminatorMessageTopics.EVALUATION: self.current_evaluations = message.value case TerminatorMessageTopics.MAX_EVALUATIONS: self.max_evaluations = message.value case _: return def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### decay_progress ``` decay_progress: float ``` The fraction of the run that has elapsed, in [0, 1]. A value of 0 means full mutation strength and a value of 1 means no mutation at all. The ratio must never leave \[0, 1\]: a negative `1 - progress` would be raised to the power `b` below, which yields a complex number for a fractional `b` and overflows the float range for an integral one. Returns: | Name | Type | Description | | ------- | ------- | ------------------------------------------------------------------------------- | | `float` | `float` | the elapsed fraction of the run, clamped to [0, 1]. Zero if no budget is known. | ##### interested_topics ``` interested_topics ``` The message topics that the mutation operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[MutationMessageTopics]] ``` The message topics provided by the mutation operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, max_generations: int | None = None, mutation_probability: float | None = None, b: float = 5.0, ) ``` Initialize a Non-uniform mutation operator. Parameters: | Name | Type | Description | Default | | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | The optimization problem definition. | *required* | | `seed` | `int` | Random number generator seed for reproducibility. | *required* | | `verbosity` | `int` | The verbosity level of the operator. See the provided_topics attribute to see what messages are provided at each verbosity level. Recommended value is 1. | *required* | | `publisher` | `Publisher` | The publisher to which the operator will send messages. | *required* | | `max_generations` | \`int | None\` | Maximum number of generations in the evolutionary run, used to scale mutation decay. Defaults to None, in which case the budget reported by the terminator is used, falling back to the number of function evaluations if the terminator does not bound the number of generations. Prefer leaving this as None: a value that disagrees with the terminator makes the decay schedule finish too early or not at all. | | `mutation_probability` | \`float | None\` | Probability of mutating each gene. If None, defaults to 1 / number of variables. | | `b` | `float` | Non-uniform mutation decay parameter. Higher values cause faster reduction in mutation strength over generations. | `5.0` | Source code in `desdeo/emo/operators/mutation.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, max_generations: int | None = None, mutation_probability: float | None = None, b: float = 5.0, # decay parameter ): """Initialize a Non-uniform mutation operator. Args: problem (Problem): The optimization problem definition. seed (int): Random number generator seed for reproducibility. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. max_generations (int | None): Maximum number of generations in the evolutionary run, used to scale mutation decay. Defaults to None, in which case the budget reported by the terminator is used, falling back to the number of function evaluations if the terminator does not bound the number of generations. Prefer leaving this as None: a value that disagrees with the terminator makes the decay schedule finish too early or not at all. mutation_probability (float | None): Probability of mutating each gene. If None, defaults to 1 / number of variables. b (float): Non-uniform mutation decay parameter. Higher values cause faster reduction in mutation strength over generations. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) if max_generations is not None and max_generations <= 0: raise ValueError(f"max_generations must be a positive integer, got {max_generations}.") self.rng = np.random.default_rng(seed) self.seed = seed self.b = b self.current_generation = 0 self.max_generations = max_generations self.current_evaluations = 0 self.max_evaluations: int | None = None # Budget reported by the terminator, used when max_generations was not given explicitly. self.reported_max_generations: int | None = None self._warned_past_budget = False self.mutation_probability = ( 1 / len(self.variable_symbols) if mutation_probability is None else mutation_probability ) ``` ##### \_mutate_value ``` _mutate_value( x: float, lower_bound: float, upper_bound: float, mutation_threshold: float = 0.5, ) -> float ``` Apply non-uniform mutation to a single float value. Parameters: | Name | Type | Description | Default | | -------------------- | ------- | -------------------------------------------- | ---------- | | `x` | `float` | The current value of the gene to be mutated. | *required* | | `lower_bound` | `float` | The lower bound of the gene. | *required* | | `upper_bound` | `float` | The upper bound of the gene. | *required* | | `mutation_threshold` | `float` | The mutation threshold. Defaults to 0.5. | `0.5` | Returns: | Name | Type | Description | | ------- | ------- | --------------------------------------------------------- | | `float` | `float` | The mutated gene value, clipped within the bounds [l, u]. | Source code in `desdeo/emo/operators/mutation.py` ``` def _mutate_value(self, x: float, lower_bound: float, upper_bound: float, mutation_threshold: float = 0.5) -> float: """Apply non-uniform mutation to a single float value. Args: x (float): The current value of the gene to be mutated. lower_bound (float): The lower bound of the gene. upper_bound (float): The upper bound of the gene. mutation_threshold (float): The mutation threshold. Defaults to 0.5. Returns: float: The mutated gene value, clipped within the bounds [l, u]. """ r = self.rng.uniform(0, 1) # Random number to choose direction b = self.b u_rand = self.rng.uniform(0, 1) # Random number for mutation strength tau = (1 - self.decay_progress) ** b if r <= mutation_threshold: y = upper_bound - x delta = y * (1 - u_rand**tau) xm = x + delta else: y = x - lower_bound delta = y * (1 - u_rand**tau) xm = x - delta return np.clip(xm, lower_bound, upper_bound) ``` ##### do ``` do( offsprings: DataFrame, parents: DataFrame ) -> pl.DataFrame ``` Perform non-uniform mutation. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ----------------------------------------------------------------------------------- | ---------- | | `offsprings` | `DataFrame` | The current offspring population to mutate. Each row corresponds to one individual. | *required* | | `parents` | `DataFrame` | The parent population (not used in mutation but passed for interface consistency). | *required* | Returns: | Type | Description | | ----------- | ----------------------------------------------------------------------------------------------------- | | `DataFrame` | pl.DataFrame: A new offspring population with mutated values applied. Returned as a Polars DataFrame. | Source code in `desdeo/emo/operators/mutation.py` ``` def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Perform non-uniform mutation. Args: offsprings (pl.DataFrame): The current offspring population to mutate. Each row corresponds to one individual. parents (pl.DataFrame): The parent population (not used in mutation but passed for interface consistency). Returns: pl.DataFrame: A new offspring population with mutated values applied. Returned as a Polars DataFrame. """ self.offspring_original = copy.copy(offsprings) self.parents = parents population = offsprings.to_numpy(writable=True).astype(float) bounds = list(zip(self.lower_bounds, self.upper_bounds, self.is_discrete, strict=True)) for i in range(population.shape[0]): for j, (lower_bound, upper_bound, discrete) in enumerate(bounds): if self.rng.random() < self.mutation_probability: mutated = self._mutate_value(population[i, j], lower_bound, upper_bound) # Round to keep the integer domain. `np.round` rather than `round`, which # raises on the NaN some crossover operators produce. population[i, j] = np.round(mutated) if discrete else mutated self.offspring = pl.from_numpy(population, schema=self.variable_symbols, orient="row").cast(pl.Float64) self.notify() return self.offspring ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the mutation operator. Source code in `desdeo/emo/operators/mutation.py` ``` def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### update ``` update(message: Message) ``` Track the progress of the run (used to reduce mutation strength over time). Source code in `desdeo/emo/operators/mutation.py` ``` def update(self, message: Message): """Track the progress of the run (used to reduce mutation strength over time).""" if not isinstance(message.topic, TerminatorMessageTopics): return if not isinstance(message.value, int): return match message.topic: case TerminatorMessageTopics.GENERATION: self.current_generation = message.value case TerminatorMessageTopics.MAX_GENERATIONS: self.reported_max_generations = message.value case TerminatorMessageTopics.EVALUATION: self.current_evaluations = message.value case TerminatorMessageTopics.MAX_EVALUATIONS: self.max_evaluations = message.value case _: return ``` #### PowerMutation Bases: `BaseMutation` Implements the Power Mutation (PM) operator for real and integer variables. Source code in `desdeo/emo/operators/mutation.py` ``` class PowerMutation(BaseMutation): """Implements the Power Mutation (PM) operator for real and integer variables.""" @property def provided_topics(self) -> dict[int, Sequence[MutationMessageTopics]]: """The message topics provided by the mutation operator.""" return { 0: [], 1: [MutationMessageTopics.MUTATION_PROBABILITY], 2: [ MutationMessageTopics.MUTATION_PROBABILITY, MutationMessageTopics.OFFSPRING_ORIGINAL, MutationMessageTopics.PARENTS, MutationMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics that the mutation operator listens to (none in this case).""" return [] def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, p: float = 1.5, mutation_probability: float | None = None, ): """Initialize the PowerMutation operator. Args: problem (Problem): The problem definition containing variable bounds and types. seed (int): Random seed for reproducibility. p (float): Power distribution parameter. Controls the perturbation magnitude. Default is 1.5. mutation_probability (float | None): Per-variable mutation probability. Defaults to 1/n. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.p = p self.mutation_probability = ( mutation_probability if mutation_probability is not None else 1 / len(self.variable_symbols) ) self.rng = np.random.default_rng(seed) self.seed = seed def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Apply Power Mutation to the given offspring population. Args: offsprings (pl.DataFrame): The offspring population to mutate. parents (pl.DataFrame): The parent population Returns: pl.DataFrame: Mutated offspring population. """ self.offspring_original = copy.copy(offsprings) self.parents = parents if self.mutation_probability == 0.0: self.offspring = offsprings.clone() self.notify() return self.offspring population = offsprings.to_numpy(writable=True).astype(float) mutation_mask = self.rng.random(population.shape) < self.mutation_probability mutated = population.copy() bounds = zip(self.lower_bounds, self.upper_bounds, self.is_discrete, strict=True) for i, (lower_bound, upper_bound, discrete) in enumerate(bounds): if upper_bound == lower_bound: # A fixed variable has a single feasible value, and scaling by the width of an # empty interval would divide by zero. Leave the column as it is. continue x_i = population[:, i] u_i = self.rng.random(len(x_i)) # uniform random number s_i = u_i ** (1 / self.p) # random number that follows the power distribution r_i = self.rng.random(len(x_i)) # another uniform random number direction = ((x_i - lower_bound) / (upper_bound - lower_bound)) < r_i # used as condition xi_mutated = np.where(direction, x_i - s_i * (x_i - lower_bound), x_i + s_i * (upper_bound - x_i)) if discrete: # Round after float mutation to keep the integer domain. xi_mutated = np.round(xi_mutated) # Apply mutation based on mask mutated[:, i] = np.where(mutation_mask[:, i], xi_mutated, x_i) # Convert back to DataFrame self.offspring = ( pl.from_numpy(mutated, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring def update(self, *_, **__): """No update logic needed.""" def state(self) -> Sequence[Message]: """Return mutation-related state messages based on verbosity level. Returns: List of messages reporting mutation probability, input, and output (at higher verbosity). """ if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # Verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics that the mutation operator listens to (none in this case). ##### provided_topics ``` provided_topics: dict[int, Sequence[MutationMessageTopics]] ``` The message topics provided by the mutation operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, p: float = 1.5, mutation_probability: float | None = None, ) ``` Initialize the PowerMutation operator. Parameters: | Name | Type | Description | Default | | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | | `problem` | `Problem` | The problem definition containing variable bounds and types. | *required* | | `seed` | `int` | Random seed for reproducibility. | *required* | | `p` | `float` | Power distribution parameter. Controls the perturbation magnitude. Default is 1.5. | `1.5` | | `mutation_probability` | \`float | None\` | Per-variable mutation probability. Defaults to 1/n. | | `verbosity` | `int` | The verbosity level of the operator. See the provided_topics attribute to see what messages are provided at each verbosity level. Recommended value is 1. | *required* | | `publisher` | `Publisher` | The publisher to which the operator will send messages. | *required* | Source code in `desdeo/emo/operators/mutation.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, p: float = 1.5, mutation_probability: float | None = None, ): """Initialize the PowerMutation operator. Args: problem (Problem): The problem definition containing variable bounds and types. seed (int): Random seed for reproducibility. p (float): Power distribution parameter. Controls the perturbation magnitude. Default is 1.5. mutation_probability (float | None): Per-variable mutation probability. Defaults to 1/n. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. """ super().__init__(problem, verbosity=verbosity, publisher=publisher) self.p = p self.mutation_probability = ( mutation_probability if mutation_probability is not None else 1 / len(self.variable_symbols) ) self.rng = np.random.default_rng(seed) self.seed = seed ``` ##### do ``` do( offsprings: DataFrame, parents: DataFrame ) -> pl.DataFrame ``` Apply Power Mutation to the given offspring population. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ----------------------------------- | ---------- | | `offsprings` | `DataFrame` | The offspring population to mutate. | *required* | | `parents` | `DataFrame` | The parent population | *required* | Returns: | Type | Description | | ----------- | ------------------------------------------- | | `DataFrame` | pl.DataFrame: Mutated offspring population. | Source code in `desdeo/emo/operators/mutation.py` ``` def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Apply Power Mutation to the given offspring population. Args: offsprings (pl.DataFrame): The offspring population to mutate. parents (pl.DataFrame): The parent population Returns: pl.DataFrame: Mutated offspring population. """ self.offspring_original = copy.copy(offsprings) self.parents = parents if self.mutation_probability == 0.0: self.offspring = offsprings.clone() self.notify() return self.offspring population = offsprings.to_numpy(writable=True).astype(float) mutation_mask = self.rng.random(population.shape) < self.mutation_probability mutated = population.copy() bounds = zip(self.lower_bounds, self.upper_bounds, self.is_discrete, strict=True) for i, (lower_bound, upper_bound, discrete) in enumerate(bounds): if upper_bound == lower_bound: # A fixed variable has a single feasible value, and scaling by the width of an # empty interval would divide by zero. Leave the column as it is. continue x_i = population[:, i] u_i = self.rng.random(len(x_i)) # uniform random number s_i = u_i ** (1 / self.p) # random number that follows the power distribution r_i = self.rng.random(len(x_i)) # another uniform random number direction = ((x_i - lower_bound) / (upper_bound - lower_bound)) < r_i # used as condition xi_mutated = np.where(direction, x_i - s_i * (x_i - lower_bound), x_i + s_i * (upper_bound - x_i)) if discrete: # Round after float mutation to keep the integer domain. xi_mutated = np.round(xi_mutated) # Apply mutation based on mask mutated[:, i] = np.where(mutation_mask[:, i], xi_mutated, x_i) # Convert back to DataFrame self.offspring = ( pl.from_numpy(mutated, schema=self.variable_symbols, orient="row").select(pl.all()).cast(pl.Float64) ) self.notify() return self.offspring ``` ##### state ``` state() -> Sequence[Message] ``` Return mutation-related state messages based on verbosity level. Returns: | Type | Description | | ------------------- | ----------------------------------------------------------------------------------------- | | `Sequence[Message]` | List of messages reporting mutation probability, input, and output (at higher verbosity). | Source code in `desdeo/emo/operators/mutation.py` ``` def state(self) -> Sequence[Message]: """Return mutation-related state messages based on verbosity level. Returns: List of messages reporting mutation probability, input, and output (at higher verbosity). """ if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # Verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### update ``` update(*_, **__) ``` No update logic needed. Source code in `desdeo/emo/operators/mutation.py` ``` def update(self, *_, **__): """No update logic needed.""" ``` #### SelfAdaptiveGaussianMutation Bases: `BaseMutation` Self-adaptive Gaussian mutation for real-coded evolutionary algorithms. Evolves both solution vector and mutation step sizes (strategy parameters). Source code in `desdeo/emo/operators/mutation.py` ``` class SelfAdaptiveGaussianMutation(BaseMutation): """Self-adaptive Gaussian mutation for real-coded evolutionary algorithms. Evolves both solution vector and mutation step sizes (strategy parameters). """ @property def provided_topics(self) -> dict[int, Sequence[MutationMessageTopics]]: """The message topics provided by the mutation operator.""" return { 0: [], 1: [ MutationMessageTopics.MUTATION_PROBABILITY, ], 2: [ MutationMessageTopics.MUTATION_PROBABILITY, MutationMessageTopics.OFFSPRING_ORIGINAL, MutationMessageTopics.PARENTS, MutationMessageTopics.OFFSPRINGS, ], } @property def interested_topics(self): """The message topics that the mutation operator is interested in.""" return [] def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ): """Initialize the self-adaptive Gaussian mutation operator. Args: problem (Problem): The optimization problem definition, including variable bounds and types. seed (int): Seed for the random number generator to ensure reproducibility. mutation_probability (float | None): Probability of mutating each gene. If None, it defaults to 1 divided by the number of variables. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. Attributes: rng (Generator): NumPy random number generator initialized with the given seed. seed (int): The seed used for reproducibility. num_vars (int): Number of variables in the problem. mutation_probability (float): Probability of mutating each gene. tau_prime (float): Global learning rate, used in step size adaptation. tau (float): Local learning rate, used in step size adaptation. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher) self.rng = np.random.default_rng(seed) self.seed = seed self.num_vars = len(self.variable_symbols) self.mutation_probability = 1 / self.num_vars if mutation_probability is None else mutation_probability self.tau_prime = 1 / np.sqrt(2 * self.num_vars) self.tau = 1 / np.sqrt(2 * np.sqrt(self.num_vars)) # Per-gene step sizes, adapted on each call and carried over across generations. self.step_sizes: np.ndarray | None = None def do( self, offsprings: pl.DataFrame, parents: pl.DataFrame, ) -> pl.DataFrame: """Apply self-adaptive Gaussian mutation. The per-gene step sizes are adapted on every call and stored in `self.step_sizes`, so that the adaptation carries over across generations. Args: offsprings (pl.DataFrame): Current offspring population. parents (pl.DataFrame): Parent population. Returns: pl.DataFrame: The mutated offspring population. """ self.offspring_original = offsprings self.parents = parents offspring_array = offsprings.to_numpy(writable=True).astype(float) if self.step_sizes is None or self.step_sizes.shape != offspring_array.shape: self.step_sizes = np.full_like(offspring_array, fill_value=0.1) new_offspring, self.step_sizes = self._mutation(offspring_array, self.step_sizes) mutated_df = pl.from_numpy(new_offspring, schema=self.variable_symbols, orient="row").cast(pl.Float64) self.offspring = mutated_df self.notify() return mutated_df def _mutation(self, variables: np.ndarray, eta: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Perform the self-adaptive mutation. Args: variables (np.ndarray): Current offspring population as a NumPy array. eta (np.ndarray): Current step sizes for mutation. Returns: tuple[np.ndarray, np.ndarray]: Mutated population and updated step sizes. """ new_variables = variables.copy() new_eta = eta.copy() for i in range(variables.shape[0]): common_noise = self.rng.normal() for j in range(variables.shape[1]): if self.rng.random() < self.mutation_probability: rnd_number = self.rng.normal() # random number in the interval [0, 1] new_eta[i, j] *= np.exp(self.tau_prime * common_noise + self.tau * rnd_number) new_variables[i, j] += new_eta[i, j] * rnd_number # Gaussian noise is unbounded, so keep the offspring inside the feasible box. Without this # the operator relies on a repair function that the templates only apply afterwards. new_variables = np.clip(new_variables, self.lower_bounds, self.upper_bounds) return new_variables, new_eta def update(self, *_, **__): """Do nothing.""" def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### interested_topics ``` interested_topics ``` The message topics that the mutation operator is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[MutationMessageTopics]] ``` The message topics provided by the mutation operator. ##### __init__ ``` __init__( *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ) ``` Initialize the self-adaptive Gaussian mutation operator. Parameters: | Name | Type | Description | Default | | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | `problem` | `Problem` | The optimization problem definition, including variable bounds and types. | *required* | | `seed` | `int` | Seed for the random number generator to ensure reproducibility. | *required* | | `mutation_probability` | \`float | None\` | Probability of mutating each gene. If None, it defaults to 1 divided by the number of variables. | | `verbosity` | `int` | The verbosity level of the operator. See the provided_topics attribute to see what messages are provided at each verbosity level. Recommended value is 1. | *required* | | `publisher` | `Publisher` | The publisher to which the operator will send messages. | *required* | Attributes: | Name | Type | Description | | ---------------------- | ----------- | -------------------------------------------------------------- | | `rng` | `Generator` | NumPy random number generator initialized with the given seed. | | `seed` | `int` | The seed used for reproducibility. | | `num_vars` | `int` | Number of variables in the problem. | | `mutation_probability` | `float` | Probability of mutating each gene. | | `tau_prime` | `float` | Global learning rate, used in step size adaptation. | | `tau` | `float` | Local learning rate, used in step size adaptation. | Source code in `desdeo/emo/operators/mutation.py` ``` def __init__( self, *, problem: Problem, seed: int, verbosity: int, publisher: Publisher, mutation_probability: float | None = None, ): """Initialize the self-adaptive Gaussian mutation operator. Args: problem (Problem): The optimization problem definition, including variable bounds and types. seed (int): Seed for the random number generator to ensure reproducibility. mutation_probability (float | None): Probability of mutating each gene. If None, it defaults to 1 divided by the number of variables. verbosity (int): The verbosity level of the operator. See the `provided_topics` attribute to see what messages are provided at each verbosity level. Recommended value is 1. publisher (Publisher): The publisher to which the operator will send messages. Attributes: rng (Generator): NumPy random number generator initialized with the given seed. seed (int): The seed used for reproducibility. num_vars (int): Number of variables in the problem. mutation_probability (float): Probability of mutating each gene. tau_prime (float): Global learning rate, used in step size adaptation. tau (float): Local learning rate, used in step size adaptation. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher) self.rng = np.random.default_rng(seed) self.seed = seed self.num_vars = len(self.variable_symbols) self.mutation_probability = 1 / self.num_vars if mutation_probability is None else mutation_probability self.tau_prime = 1 / np.sqrt(2 * self.num_vars) self.tau = 1 / np.sqrt(2 * np.sqrt(self.num_vars)) # Per-gene step sizes, adapted on each call and carried over across generations. self.step_sizes: np.ndarray | None = None ``` ##### \_mutation ``` _mutation( variables: ndarray, eta: ndarray ) -> tuple[np.ndarray, np.ndarray] ``` Perform the self-adaptive mutation. Parameters: | Name | Type | Description | Default | | ----------- | --------- | ---------------------------------------------- | ---------- | | `variables` | `ndarray` | Current offspring population as a NumPy array. | *required* | | `eta` | `ndarray` | Current step sizes for mutation. | *required* | Returns: | Type | Description | | ------------------------- | --------------------------------------------------------------------------- | | `tuple[ndarray, ndarray]` | tuple\[np.ndarray, np.ndarray\]: Mutated population and updated step sizes. | Source code in `desdeo/emo/operators/mutation.py` ``` def _mutation(self, variables: np.ndarray, eta: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Perform the self-adaptive mutation. Args: variables (np.ndarray): Current offspring population as a NumPy array. eta (np.ndarray): Current step sizes for mutation. Returns: tuple[np.ndarray, np.ndarray]: Mutated population and updated step sizes. """ new_variables = variables.copy() new_eta = eta.copy() for i in range(variables.shape[0]): common_noise = self.rng.normal() for j in range(variables.shape[1]): if self.rng.random() < self.mutation_probability: rnd_number = self.rng.normal() # random number in the interval [0, 1] new_eta[i, j] *= np.exp(self.tau_prime * common_noise + self.tau * rnd_number) new_variables[i, j] += new_eta[i, j] * rnd_number # Gaussian noise is unbounded, so keep the offspring inside the feasible box. Without this # the operator relies on a repair function that the templates only apply afterwards. new_variables = np.clip(new_variables, self.lower_bounds, self.upper_bounds) return new_variables, new_eta ``` ##### do ``` do( offsprings: DataFrame, parents: DataFrame ) -> pl.DataFrame ``` Apply self-adaptive Gaussian mutation. The per-gene step sizes are adapted on every call and stored in `self.step_sizes`, so that the adaptation carries over across generations. Parameters: | Name | Type | Description | Default | | ------------ | ----------- | ----------------------------- | ---------- | | `offsprings` | `DataFrame` | Current offspring population. | *required* | | `parents` | `DataFrame` | Parent population. | *required* | Returns: | Type | Description | | ----------- | ----------------------------------------------- | | `DataFrame` | pl.DataFrame: The mutated offspring population. | Source code in `desdeo/emo/operators/mutation.py` ``` def do( self, offsprings: pl.DataFrame, parents: pl.DataFrame, ) -> pl.DataFrame: """Apply self-adaptive Gaussian mutation. The per-gene step sizes are adapted on every call and stored in `self.step_sizes`, so that the adaptation carries over across generations. Args: offsprings (pl.DataFrame): Current offspring population. parents (pl.DataFrame): Parent population. Returns: pl.DataFrame: The mutated offspring population. """ self.offspring_original = offsprings self.parents = parents offspring_array = offsprings.to_numpy(writable=True).astype(float) if self.step_sizes is None or self.step_sizes.shape != offspring_array.shape: self.step_sizes = np.full_like(offspring_array, fill_value=0.1) new_offspring, self.step_sizes = self._mutation(offspring_array, self.step_sizes) mutated_df = pl.from_numpy(new_offspring, schema=self.variable_symbols, orient="row").cast(pl.Float64) self.offspring = mutated_df self.notify() return mutated_df ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the mutation operator. Source code in `desdeo/emo/operators/mutation.py` ``` def state(self) -> Sequence[Message]: """Return the state of the mutation operator.""" if self.offspring_original is None or self.parents is None or self.offspring is None: return [] if self.verbosity == 0: return [] if self.verbosity == 1: return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] # verbosity == 2 return [ PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRING_ORIGINAL, source=self.__class__.__name__, value=self.offspring_original, ), PolarsDataFrameMessage( topic=MutationMessageTopics.PARENTS, source=self.__class__.__name__, value=self.parents, ), PolarsDataFrameMessage( topic=MutationMessageTopics.OFFSPRINGS, source=self.__class__.__name__, value=self.offspring, ), FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=self.mutation_probability, ), ] ``` ##### update ``` update(*_, **__) ``` Do nothing. Source code in `desdeo/emo/operators/mutation.py` ``` def update(self, *_, **__): """Do nothing.""" ``` ## Selection operators ### desdeo.emo.operators.selection The base class for selection operators. Some operators should be rewritten. TODO:@light-weaver #### AGEMOEA2Selector Bases: `_FitnessPublishingSelector` The environmental selection of AGE-MOEA-II, as the author's code implements it. This follows Panichella's own implementation, the replication package of the 2022 paper (Zenodo 6462859), whose code PlatEMO 4.15 ships unchanged as AGE-MOEA-II. It leaves out one step of that code, described below. Parents and offspring are sorted into nondominated fronts, which are copied whole while they fit. The front that does not fit is ranked by survival score and cut. First-front scores come from the front's geometry (`agemoea2_survival_score`). A solution of a later front scores `1 / ||f - z||_p`, where `f` are its raw objective values, `z` holds the smallest value of each objective in the merged population, and `p` is the first front's curvature. On a constrained problem the fronts follow constrained domination, as PlatEMO's sorting does. The author's code departs from the papers in three places, and this selector follows the code: - Normalization keeps a negative or infinite intercept (`agemoea2_normalize`), where the 2019 paper falls back to min-max constants. - Later fronts are scored on raw objectives. The 2019 paper (Section 3.2) normalizes them with the first front's constants. - The last first-front solution of the greedy scoring loop keeps the score 0. NaN, which degenerate fronts produce through `0 / 0`, is handled the way MATLAB handles it: `min` and `max` skip it, and the descending sort that orders the cut front puts it first. The author's code also rounds every objective to 12 decimals before sorting. That step is left out here. It is an absolute threshold, so what it does depends on the objectives' scale. On 3-objective DTLZ4 its effect is large: from a random start, 47 of 50 runs with the rounding reached the whole front, and 26 of 50 without it. The fitness published for the binary tournament ranks solutions by front first and survival score second, with NaN below every number and equal scores tied, as the author's `TournamentSelection(2, N, FrontNo, -CrowdDis)` compares them. pymoo 0.6.2's AGEMOEA2 differs from the author's code in several places: it picks the extreme points by distance to the axes, falls back to min-max constants on a negative intercept, normalizes later fronts, and never scores the cut front unless it is the first. References Panichella, A. (2022). An improved Pareto front modeling algorithm for large-scale many-objective optimization. In Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '22) (pp. 565-573). https://doi.org/10.1145/3512290.3528732 Panichella, A. (2019). An adaptive evolutionary algorithm based on non-euclidean geometry for many-objective optimization. In Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '19) (pp. 595-603). https://doi.org/10.1145/3321707.3321839 Panichella, A. (2022). An improved Pareto front modeling algorithm for large-scale many-objective optimization [Source code]. Zenodo. https://doi.org/10.5281/zenodo.6462859 Source code in `desdeo/emo/operators/selection.py` ``` class AGEMOEA2Selector(_FitnessPublishingSelector): """The environmental selection of AGE-MOEA-II, as the author's code implements it. This follows Panichella's own implementation, the replication package of the 2022 paper (Zenodo 6462859), whose code PlatEMO 4.15 ships unchanged as AGE-MOEA-II. It leaves out one step of that code, described below. Parents and offspring are sorted into nondominated fronts, which are copied whole while they fit. The front that does not fit is ranked by survival score and cut. First-front scores come from the front's geometry (`agemoea2_survival_score`). A solution of a later front scores `1 / ||f - z||_p`, where `f` are its raw objective values, `z` holds the smallest value of each objective in the merged population, and `p` is the first front's curvature. On a constrained problem the fronts follow constrained domination, as PlatEMO's sorting does. The author's code departs from the papers in three places, and this selector follows the code: - Normalization keeps a negative or infinite intercept (`agemoea2_normalize`), where the 2019 paper falls back to min-max constants. - Later fronts are scored on raw objectives. The 2019 paper (Section 3.2) normalizes them with the first front's constants. - The last first-front solution of the greedy scoring loop keeps the score 0. NaN, which degenerate fronts produce through `0 / 0`, is handled the way MATLAB handles it: `min` and `max` skip it, and the descending sort that orders the cut front puts it first. The author's code also rounds every objective to 12 decimals before sorting. That step is left out here. It is an absolute threshold, so what it does depends on the objectives' scale. On 3-objective DTLZ4 its effect is large: from a random start, 47 of 50 runs with the rounding reached the whole front, and 26 of 50 without it. The fitness published for the binary tournament ranks solutions by front first and survival score second, with NaN below every number and equal scores tied, as the author's `TournamentSelection(2, N, FrontNo, -CrowdDis)` compares them. pymoo 0.6.2's AGEMOEA2 differs from the author's code in several places: it picks the extreme points by distance to the axes, falls back to min-max constants on a negative intercept, normalizes later fronts, and never scores the cut front unless it is the first. References: Panichella, A. (2022). An improved Pareto front modeling algorithm for large-scale many-objective optimization. In Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '22) (pp. 565-573). https://doi.org/10.1145/3512290.3528732 Panichella, A. (2019). An adaptive evolutionary algorithm based on non-euclidean geometry for many-objective optimization. In Proceedings of the Genetic and Evolutionary Computation Conference (GECCO '19) (pp. 595-603). https://doi.org/10.1145/3321707.3321839 Panichella, A. (2022). An improved Pareto front modeling algorithm for large-scale many-objective optimization [Source code]. Zenodo. https://doi.org/10.5281/zenodo.6462859 """ def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Select the next population from parents and offspring (Panichella 2022, Algorithm 2, lines 5-16). Args: parents (tuple[SolutionType, pl.DataFrame]): the parents and their outputs. offsprings (tuple[SolutionType, pl.DataFrame]): the offspring and their outputs. Empty in the first generation. Returns: tuple[SolutionType, pl.DataFrame]: the selected solutions and their outputs. """ solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy().astype(float) fronts = constrained_fronts(targets, total_constraint_violation(outputs, self.constraints_symbols)) # The front reached when N solutions have been sorted is the one to cut, even when it fits exactly. last = min(int(np.searchsorted(np.cumsum(fronts.sum(axis=1)), self.population_size)), len(fronts) - 1) score = np.zeros(len(targets)) score[fronts[0]], p = agemoea2_survival_score(targets[fronts[0]]) ideal = targets.min(axis=0) for d in range(1, last + 1): with np.errstate(divide="ignore"): score[fronts[d]] = 1.0 / _lp_norm(targets[fronts[d]] - ideal, p) chosen = [int(i) for d in range(last) for i in np.flatnonzero(fronts[d])] cut = np.flatnonzero(fronts[last]) # Descending, NaN first, ties in index order, as MATLAB's sort(..., 'descend'). order = np.lexsort((-np.where(np.isnan(score[cut]), 0.0, score[cut]), ~np.isnan(score[cut]))) chosen = sorted(chosen + [int(i) for i in cut[order[: self.population_size - len(chosen)]]]) rank = np.argmax(fronts[:, chosen], axis=0) kept = np.where(np.isnan(score[chosen]), -np.inf, score[chosen]) fitness = np.zeros(len(chosen)) for d in np.unique(rank): members = np.flatnonzero(rank == d) levels = np.unique(kept[members], return_inverse=True)[1] # Front first, survival score second; positive and higher-is-better for the tournament's argmax. fitness[members] = (rank.max() + 1.0 - d) + (levels + 1) / (levels.max() + 2) self.curvature = p return self._finish(solutions, outputs, chosen, fitness) ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Select the next population from parents and offspring (Panichella 2022, Algorithm 2, lines 5-16). Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | --------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | the parents and their outputs. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | the offspring and their outputs. Empty in the first generation. | *required* | Returns: | Type | Description | | -------------------------------- | ------------------------------------------------------------------------------ | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: the selected solutions and their outputs. | Source code in `desdeo/emo/operators/selection.py` ``` def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Select the next population from parents and offspring (Panichella 2022, Algorithm 2, lines 5-16). Args: parents (tuple[SolutionType, pl.DataFrame]): the parents and their outputs. offsprings (tuple[SolutionType, pl.DataFrame]): the offspring and their outputs. Empty in the first generation. Returns: tuple[SolutionType, pl.DataFrame]: the selected solutions and their outputs. """ solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy().astype(float) fronts = constrained_fronts(targets, total_constraint_violation(outputs, self.constraints_symbols)) # The front reached when N solutions have been sorted is the one to cut, even when it fits exactly. last = min(int(np.searchsorted(np.cumsum(fronts.sum(axis=1)), self.population_size)), len(fronts) - 1) score = np.zeros(len(targets)) score[fronts[0]], p = agemoea2_survival_score(targets[fronts[0]]) ideal = targets.min(axis=0) for d in range(1, last + 1): with np.errstate(divide="ignore"): score[fronts[d]] = 1.0 / _lp_norm(targets[fronts[d]] - ideal, p) chosen = [int(i) for d in range(last) for i in np.flatnonzero(fronts[d])] cut = np.flatnonzero(fronts[last]) # Descending, NaN first, ties in index order, as MATLAB's sort(..., 'descend'). order = np.lexsort((-np.where(np.isnan(score[cut]), 0.0, score[cut]), ~np.isnan(score[cut]))) chosen = sorted(chosen + [int(i) for i in cut[order[: self.population_size - len(chosen)]]]) rank = np.argmax(fronts[:, chosen], axis=0) kept = np.where(np.isnan(score[chosen]), -np.inf, score[chosen]) fitness = np.zeros(len(chosen)) for d in np.unique(rank): members = np.flatnonzero(rank == d) levels = np.unique(kept[members], return_inverse=True)[1] # Front first, survival score second; positive and higher-is-better for the tournament's argmax. fitness[members] = (rank.max() + 1.0 - d) + (levels + 1) / (levels.max() + 2) self.curvature = p return self._finish(solutions, outputs, chosen, fitness) ``` #### BaseDecompositionSelector Bases: `BaseSelector` Base class for decomposition based selection operators. Source code in `desdeo/emo/operators/selection.py` ``` class BaseDecompositionSelector(BaseSelector): """Base class for decomposition based selection operators.""" def __init__( self, problem: Problem, reference_vector_options: ReferenceVectorOptions, verbosity: int, publisher: Publisher, invert_reference_vectors: bool = False, seed: int = 0, ): """Initialize the base decomposition based selector. Args: problem (Problem): the problem being solved. reference_vector_options (ReferenceVectorOptions): options for creating and adapting the reference vectors. verbosity (int): the verbosity level of the operator. publisher (Publisher): the publisher used to communicate with other operators. invert_reference_vectors (bool, optional): whether to invert the reference vectors. Defaults to False. seed (int, optional): the random seed. Defaults to 0. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) self.reference_vector_options = reference_vector_options self.invert_reference_vectors = invert_reference_vectors self.reference_vectors: np.ndarray self.reference_vectors_initial: np.ndarray if self.reference_vector_options.creation_type == "s_energy": self._create_s_energy() else: self._create_simplex() if self.reference_vector_options.reference_point: corrected_rp = np.array( [ self.reference_vector_options.reference_point[x] * self.maximization_mult[x] for x in self.objective_symbols ] ) self.interactive_adapt_3( corrected_rp, translation_param=self.reference_vector_options.adaptation_distance, ) elif self.reference_vector_options.preferred_solutions: corrected_sols = np.array( [ np.array(self.reference_vector_options.preferred_solutions[x]) * self.maximization_mult[x] for x in self.objective_symbols ] ).T self.interactive_adapt_1( corrected_sols, translation_param=self.reference_vector_options.adaptation_distance, ) elif self.reference_vector_options.non_preferred_solutions: corrected_sols = np.array( [ np.array(self.reference_vector_options.non_preferred_solutions[x]) * self.maximization_mult[x] for x in self.objective_symbols ] ).T self.interactive_adapt_2( corrected_sols, predefined_distance=self.reference_vector_options.adaptation_distance, norm_order=2 if self.reference_vector_options.vector_type == "spherical" else 1, ) elif self.reference_vector_options.preferred_ranges: corrected_ranges = np.array( [ np.array(self.reference_vector_options.preferred_ranges[x]) * self.maximization_mult[x] for x in self.objective_symbols ] ).T self.interactive_adapt_4( corrected_ranges, ) def _create_s_energy(self): """Create the reference vectors by minimizing the Riesz s-energy. Unlike the simplex lattice, this honours `number_of_vectors` exactly, so the population size of a decomposition-based algorithm can be chosen freely rather than being rounded down to the nearest binomial count. `lattice_resolution` is not meaningful here and is left untouched. """ vectors = create_s_energy( number_of_objectives=self.num_dims, number_of_vectors=self.reference_vector_options.number_of_vectors, seed=self.seed, ) # `invert_reference_vectors` mirrors the simplex branch, where it exists for NSGA-III. self.reference_vectors = vectors if not self.invert_reference_vectors else 1 - vectors self.reference_vectors_initial = np.copy(self.reference_vectors) self._normalize_rvs() def _create_simplex(self): """Create the reference vectors using simplex lattice design.""" def approx_lattice_resolution(number_of_vectors: int, num_dims: int) -> int: """Approximate the lattice resolution based on the number of vectors.""" temp_lattice_resolution = 0 while True: temp_lattice_resolution += 1 temp_number_of_vectors = comb( temp_lattice_resolution + num_dims - 1, num_dims - 1, exact=True, ) if temp_number_of_vectors > number_of_vectors: break return temp_lattice_resolution - 1 if self.reference_vector_options.lattice_resolution: lattice_resolution = self.reference_vector_options.lattice_resolution else: lattice_resolution = approx_lattice_resolution( self.reference_vector_options.number_of_vectors, num_dims=self.num_dims ) number_of_vectors: int = comb( lattice_resolution + self.num_dims - 1, self.num_dims - 1, exact=True, ) self.reference_vector_options.number_of_vectors = number_of_vectors self.reference_vector_options.lattice_resolution = lattice_resolution temp1 = range(1, self.num_dims + lattice_resolution) temp1 = np.array(list(combinations(temp1, self.num_dims - 1))) temp2 = np.array([range(self.num_dims - 1)] * number_of_vectors) temp = temp1 - temp2 - 1 weight = np.zeros((number_of_vectors, self.num_dims), dtype=int) weight[:, 0] = temp[:, 0] for i in range(1, self.num_dims - 1): weight[:, i] = temp[:, i] - temp[:, i - 1] weight[:, -1] = lattice_resolution - temp[:, -1] if not self.invert_reference_vectors: # todo, this currently only exists for nsga3 self.reference_vectors = weight / lattice_resolution else: self.reference_vectors = 1 - (weight / lattice_resolution) self.reference_vectors_initial = np.copy(self.reference_vectors) self._normalize_rvs() def _normalize_rvs(self): """Normalize the reference vectors to a unit hypersphere.""" if self.reference_vector_options.vector_type == "spherical": norm = np.linalg.norm(self.reference_vectors, axis=1).reshape(-1, 1) norm[norm == 0] = np.finfo(float).eps self.reference_vectors = np.divide(self.reference_vectors, norm) return if self.reference_vector_options.vector_type == "planar": if not self.invert_reference_vectors: norm = np.sum(self.reference_vectors, axis=1).reshape(-1, 1) self.reference_vectors = np.divide(self.reference_vectors, norm) return norm = np.sum(1 - self.reference_vectors, axis=1).reshape(-1, 1) self.reference_vectors = 1 - np.divide(1 - self.reference_vectors, norm) return # Not needed due to pydantic validation raise ValueError("Invalid vector type. Must be either 'spherical' or 'planar'.") def interactive_adapt_1(self, z: np.ndarray, translation_param: float) -> None: """Adapt reference vectors using the information about prefererred solution(s) selected by the Decision maker. Args: z (np.ndarray): Preferred solution(s). translation_param (float): Parameter determining how close the reference vectors are to the central vector **v** defined by using the selected solution(s) z. """ if z.shape[0] == 1: # single preferred solution # calculate new reference vectors self.reference_vectors = translation_param * self.reference_vectors_initial + ((1 - translation_param) * z) else: # multiple preferred solutions # calculate new reference vectors for each preferred solution values = [translation_param * self.reference_vectors_initial + ((1 - translation_param) * z_i) for z_i in z] # combine arrays of reference vectors into a single array and update reference vectors self.reference_vectors = np.concatenate(values) self._normalize_rvs() self.add_edge_vectors() def interactive_adapt_2(self, z: np.ndarray, predefined_distance: float, norm_order: int) -> None: """Adapt reference vectors using information about non-preferred solution(s) from the Decision maker. After the Decision maker has specified non-preferred solution(s), Euclidian distance between normalized solution vector(s) and each of the reference vectors are calculated. Those reference vectors that are **closer** than a predefined distance are either **removed** or **re-positioned** somewhere else. Note: At the moment, only the **removal** of reference vectors is supported. Repositioning of the reference vectors is **not** supported. Note: In case the Decision maker specifies multiple non-preferred solutions, the reference vector(s) for which the distance to **any** of the non-preferred solutions is less than predefined distance are removed. Note: Future developer should implement a way for a user to say: "Remove some percentage of objecive space/reference vectors" rather than giving a predefined distance value. Args: z (np.ndarray): Non-preferred solution(s). predefined_distance (float): The reference vectors that are closer than this distance are either removed or re-positioned somewhere else. Default value: 0.2 norm_order (int): Order of the norm. Default is 2, i.e., Euclidian distance. """ # calculate L1 norm of non-preferred solution(s) z = np.atleast_2d(z) norm = np.linalg.norm(z, ord=norm_order, axis=1).reshape(np.shape(z)[0], 1) # non-preferred solutions normalized v_c = np.divide(z, norm) # distances from non-preferred solution(s) to each reference vector distances = np.array( [[np.linalg.norm(solution - value, ord=2) for solution in v_c] for value in self.reference_vectors] ) # find out reference vectors that are not closer than threshold value to any non-preferred solution mask = [all(d >= predefined_distance) for d in distances] # set those reference vectors that met previous condition as new reference vectors, drop others self.reference_vectors = self.reference_vectors[mask] self._normalize_rvs() self.add_edge_vectors() def interactive_adapt_3(self, ref_point, translation_param): """Adapt reference vectors linearly towards a reference point. Then normalize. The details can be found in the following paper: Hakanen, Jussi & Chugh, Tinkle & Sindhya, Karthik & Jin, Yaochu & Miettinen, Kaisa. (2016). Connections of Reference Vectors and Different Types of Preference Information in Interactive Multiobjective Evolutionary Algorithms. Parameters ---------- ref_point : translation_param : (Default value = 0.2) """ self.reference_vectors = self.reference_vectors_initial * translation_param + ( (1 - translation_param) * ref_point ) self._normalize_rvs() self.add_edge_vectors() def interactive_adapt_4(self, preferred_ranges: np.ndarray) -> None: """Adapt reference vectors using the Decision maker's preferred range for each objective. Using these ranges, Latin hypercube sampling is applied to generate m number of samples between within these ranges, where m is the number of reference vectors. Normalized vectors constructed of these samples are then set as new reference vectors. Args: preferred_ranges (np.ndarray): Preferred lower and upper bound for each of the objective function values. """ # bounds lower_limits = np.min(preferred_ranges, axis=0) upper_limits = np.max(preferred_ranges, axis=0) # generate samples using Latin hypercube sampling lhs = LatinHypercube(d=self.num_dims, seed=self.rng) w = lhs.random(n=self.reference_vectors_initial.shape[0]) # scale between bounds w = w * (upper_limits - lower_limits) + lower_limits # set new reference vectors and normalize them self.reference_vectors = w self._normalize_rvs() self.add_edge_vectors() def add_edge_vectors(self): """Add edge vectors to the list of reference vectors. Used to cover the entire orthant when preference information is provided. """ edge_vectors = np.eye(self.reference_vectors.shape[1]) self.reference_vectors = np.vstack([self.reference_vectors, edge_vectors]) self._normalize_rvs() ``` ##### __init__ ``` __init__( problem: Problem, reference_vector_options: ReferenceVectorOptions, verbosity: int, publisher: Publisher, invert_reference_vectors: bool = False, seed: int = 0, ) ``` Initialize the base decomposition based selector. Parameters: | Name | Type | Description | Default | | -------------------------- | ------------------------ | ----------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem being solved. | *required* | | `reference_vector_options` | `ReferenceVectorOptions` | options for creating and adapting the reference vectors. | *required* | | `verbosity` | `int` | the verbosity level of the operator. | *required* | | `publisher` | `Publisher` | the publisher used to communicate with other operators. | *required* | | `invert_reference_vectors` | `bool` | whether to invert the reference vectors. Defaults to False. | `False` | | `seed` | `int` | the random seed. Defaults to 0. | `0` | Source code in `desdeo/emo/operators/selection.py` ``` def __init__( self, problem: Problem, reference_vector_options: ReferenceVectorOptions, verbosity: int, publisher: Publisher, invert_reference_vectors: bool = False, seed: int = 0, ): """Initialize the base decomposition based selector. Args: problem (Problem): the problem being solved. reference_vector_options (ReferenceVectorOptions): options for creating and adapting the reference vectors. verbosity (int): the verbosity level of the operator. publisher (Publisher): the publisher used to communicate with other operators. invert_reference_vectors (bool, optional): whether to invert the reference vectors. Defaults to False. seed (int, optional): the random seed. Defaults to 0. """ super().__init__(problem, verbosity=verbosity, publisher=publisher, seed=seed) self.reference_vector_options = reference_vector_options self.invert_reference_vectors = invert_reference_vectors self.reference_vectors: np.ndarray self.reference_vectors_initial: np.ndarray if self.reference_vector_options.creation_type == "s_energy": self._create_s_energy() else: self._create_simplex() if self.reference_vector_options.reference_point: corrected_rp = np.array( [ self.reference_vector_options.reference_point[x] * self.maximization_mult[x] for x in self.objective_symbols ] ) self.interactive_adapt_3( corrected_rp, translation_param=self.reference_vector_options.adaptation_distance, ) elif self.reference_vector_options.preferred_solutions: corrected_sols = np.array( [ np.array(self.reference_vector_options.preferred_solutions[x]) * self.maximization_mult[x] for x in self.objective_symbols ] ).T self.interactive_adapt_1( corrected_sols, translation_param=self.reference_vector_options.adaptation_distance, ) elif self.reference_vector_options.non_preferred_solutions: corrected_sols = np.array( [ np.array(self.reference_vector_options.non_preferred_solutions[x]) * self.maximization_mult[x] for x in self.objective_symbols ] ).T self.interactive_adapt_2( corrected_sols, predefined_distance=self.reference_vector_options.adaptation_distance, norm_order=2 if self.reference_vector_options.vector_type == "spherical" else 1, ) elif self.reference_vector_options.preferred_ranges: corrected_ranges = np.array( [ np.array(self.reference_vector_options.preferred_ranges[x]) * self.maximization_mult[x] for x in self.objective_symbols ] ).T self.interactive_adapt_4( corrected_ranges, ) ``` ##### \_create_s_energy ``` _create_s_energy() ``` Create the reference vectors by minimizing the Riesz s-energy. Unlike the simplex lattice, this honours `number_of_vectors` exactly, so the population size of a decomposition-based algorithm can be chosen freely rather than being rounded down to the nearest binomial count. `lattice_resolution` is not meaningful here and is left untouched. Source code in `desdeo/emo/operators/selection.py` ``` def _create_s_energy(self): """Create the reference vectors by minimizing the Riesz s-energy. Unlike the simplex lattice, this honours `number_of_vectors` exactly, so the population size of a decomposition-based algorithm can be chosen freely rather than being rounded down to the nearest binomial count. `lattice_resolution` is not meaningful here and is left untouched. """ vectors = create_s_energy( number_of_objectives=self.num_dims, number_of_vectors=self.reference_vector_options.number_of_vectors, seed=self.seed, ) # `invert_reference_vectors` mirrors the simplex branch, where it exists for NSGA-III. self.reference_vectors = vectors if not self.invert_reference_vectors else 1 - vectors self.reference_vectors_initial = np.copy(self.reference_vectors) self._normalize_rvs() ``` ##### \_create_simplex ``` _create_simplex() ``` Create the reference vectors using simplex lattice design. Source code in `desdeo/emo/operators/selection.py` ``` def _create_simplex(self): """Create the reference vectors using simplex lattice design.""" def approx_lattice_resolution(number_of_vectors: int, num_dims: int) -> int: """Approximate the lattice resolution based on the number of vectors.""" temp_lattice_resolution = 0 while True: temp_lattice_resolution += 1 temp_number_of_vectors = comb( temp_lattice_resolution + num_dims - 1, num_dims - 1, exact=True, ) if temp_number_of_vectors > number_of_vectors: break return temp_lattice_resolution - 1 if self.reference_vector_options.lattice_resolution: lattice_resolution = self.reference_vector_options.lattice_resolution else: lattice_resolution = approx_lattice_resolution( self.reference_vector_options.number_of_vectors, num_dims=self.num_dims ) number_of_vectors: int = comb( lattice_resolution + self.num_dims - 1, self.num_dims - 1, exact=True, ) self.reference_vector_options.number_of_vectors = number_of_vectors self.reference_vector_options.lattice_resolution = lattice_resolution temp1 = range(1, self.num_dims + lattice_resolution) temp1 = np.array(list(combinations(temp1, self.num_dims - 1))) temp2 = np.array([range(self.num_dims - 1)] * number_of_vectors) temp = temp1 - temp2 - 1 weight = np.zeros((number_of_vectors, self.num_dims), dtype=int) weight[:, 0] = temp[:, 0] for i in range(1, self.num_dims - 1): weight[:, i] = temp[:, i] - temp[:, i - 1] weight[:, -1] = lattice_resolution - temp[:, -1] if not self.invert_reference_vectors: # todo, this currently only exists for nsga3 self.reference_vectors = weight / lattice_resolution else: self.reference_vectors = 1 - (weight / lattice_resolution) self.reference_vectors_initial = np.copy(self.reference_vectors) self._normalize_rvs() ``` ##### \_normalize_rvs ``` _normalize_rvs() ``` Normalize the reference vectors to a unit hypersphere. Source code in `desdeo/emo/operators/selection.py` ``` def _normalize_rvs(self): """Normalize the reference vectors to a unit hypersphere.""" if self.reference_vector_options.vector_type == "spherical": norm = np.linalg.norm(self.reference_vectors, axis=1).reshape(-1, 1) norm[norm == 0] = np.finfo(float).eps self.reference_vectors = np.divide(self.reference_vectors, norm) return if self.reference_vector_options.vector_type == "planar": if not self.invert_reference_vectors: norm = np.sum(self.reference_vectors, axis=1).reshape(-1, 1) self.reference_vectors = np.divide(self.reference_vectors, norm) return norm = np.sum(1 - self.reference_vectors, axis=1).reshape(-1, 1) self.reference_vectors = 1 - np.divide(1 - self.reference_vectors, norm) return # Not needed due to pydantic validation raise ValueError("Invalid vector type. Must be either 'spherical' or 'planar'.") ``` ##### add_edge_vectors ``` add_edge_vectors() ``` Add edge vectors to the list of reference vectors. Used to cover the entire orthant when preference information is provided. Source code in `desdeo/emo/operators/selection.py` ``` def add_edge_vectors(self): """Add edge vectors to the list of reference vectors. Used to cover the entire orthant when preference information is provided. """ edge_vectors = np.eye(self.reference_vectors.shape[1]) self.reference_vectors = np.vstack([self.reference_vectors, edge_vectors]) self._normalize_rvs() ``` ##### interactive_adapt_1 ``` interactive_adapt_1( z: ndarray, translation_param: float ) -> None ``` Adapt reference vectors using the information about prefererred solution(s) selected by the Decision maker. Parameters: | Name | Type | Description | Default | | ------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------- | | `z` | `ndarray` | Preferred solution(s). | *required* | | `translation_param` | `float` | Parameter determining how close the reference vectors are to the central vector v defined by using the selected solution(s) z. | *required* | Source code in `desdeo/emo/operators/selection.py` ``` def interactive_adapt_1(self, z: np.ndarray, translation_param: float) -> None: """Adapt reference vectors using the information about prefererred solution(s) selected by the Decision maker. Args: z (np.ndarray): Preferred solution(s). translation_param (float): Parameter determining how close the reference vectors are to the central vector **v** defined by using the selected solution(s) z. """ if z.shape[0] == 1: # single preferred solution # calculate new reference vectors self.reference_vectors = translation_param * self.reference_vectors_initial + ((1 - translation_param) * z) else: # multiple preferred solutions # calculate new reference vectors for each preferred solution values = [translation_param * self.reference_vectors_initial + ((1 - translation_param) * z_i) for z_i in z] # combine arrays of reference vectors into a single array and update reference vectors self.reference_vectors = np.concatenate(values) self._normalize_rvs() self.add_edge_vectors() ``` ##### interactive_adapt_2 ``` interactive_adapt_2( z: ndarray, predefined_distance: float, norm_order: int ) -> None ``` Adapt reference vectors using information about non-preferred solution(s) from the Decision maker. After the Decision maker has specified non-preferred solution(s), Euclidian distance between normalized solution vector(s) and each of the reference vectors are calculated. Those reference vectors that are **closer** than a predefined distance are either **removed** or **re-positioned** somewhere else. Note At the moment, only the **removal** of reference vectors is supported. Repositioning of the reference vectors is **not** supported. Note In case the Decision maker specifies multiple non-preferred solutions, the reference vector(s) for which the distance to **any** of the non-preferred solutions is less than predefined distance are removed. Note Future developer should implement a way for a user to say: "Remove some percentage of objecive space/reference vectors" rather than giving a predefined distance value. Parameters: | Name | Type | Description | Default | | --------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `z` | `ndarray` | Non-preferred solution(s). | *required* | | `predefined_distance` | `float` | The reference vectors that are closer than this distance are either removed or re-positioned somewhere else. Default value: 0.2 | *required* | | `norm_order` | `int` | Order of the norm. Default is 2, i.e., Euclidian distance. | *required* | Source code in `desdeo/emo/operators/selection.py` ``` def interactive_adapt_2(self, z: np.ndarray, predefined_distance: float, norm_order: int) -> None: """Adapt reference vectors using information about non-preferred solution(s) from the Decision maker. After the Decision maker has specified non-preferred solution(s), Euclidian distance between normalized solution vector(s) and each of the reference vectors are calculated. Those reference vectors that are **closer** than a predefined distance are either **removed** or **re-positioned** somewhere else. Note: At the moment, only the **removal** of reference vectors is supported. Repositioning of the reference vectors is **not** supported. Note: In case the Decision maker specifies multiple non-preferred solutions, the reference vector(s) for which the distance to **any** of the non-preferred solutions is less than predefined distance are removed. Note: Future developer should implement a way for a user to say: "Remove some percentage of objecive space/reference vectors" rather than giving a predefined distance value. Args: z (np.ndarray): Non-preferred solution(s). predefined_distance (float): The reference vectors that are closer than this distance are either removed or re-positioned somewhere else. Default value: 0.2 norm_order (int): Order of the norm. Default is 2, i.e., Euclidian distance. """ # calculate L1 norm of non-preferred solution(s) z = np.atleast_2d(z) norm = np.linalg.norm(z, ord=norm_order, axis=1).reshape(np.shape(z)[0], 1) # non-preferred solutions normalized v_c = np.divide(z, norm) # distances from non-preferred solution(s) to each reference vector distances = np.array( [[np.linalg.norm(solution - value, ord=2) for solution in v_c] for value in self.reference_vectors] ) # find out reference vectors that are not closer than threshold value to any non-preferred solution mask = [all(d >= predefined_distance) for d in distances] # set those reference vectors that met previous condition as new reference vectors, drop others self.reference_vectors = self.reference_vectors[mask] self._normalize_rvs() self.add_edge_vectors() ``` ##### interactive_adapt_3 ``` interactive_adapt_3(ref_point, translation_param) ``` Adapt reference vectors linearly towards a reference point. Then normalize. The details can be found in the following paper: Hakanen, Jussi & Chugh, Tinkle & Sindhya, Karthik & Jin, Yaochu & Miettinen, Kaisa. (2016). Connections of Reference Vectors and Different Types of Preference Information in Interactive Multiobjective Evolutionary Algorithms. ###### Parameters ref_point : translation_param (Default value = 0.2) Source code in `desdeo/emo/operators/selection.py` ``` def interactive_adapt_3(self, ref_point, translation_param): """Adapt reference vectors linearly towards a reference point. Then normalize. The details can be found in the following paper: Hakanen, Jussi & Chugh, Tinkle & Sindhya, Karthik & Jin, Yaochu & Miettinen, Kaisa. (2016). Connections of Reference Vectors and Different Types of Preference Information in Interactive Multiobjective Evolutionary Algorithms. Parameters ---------- ref_point : translation_param : (Default value = 0.2) """ self.reference_vectors = self.reference_vectors_initial * translation_param + ( (1 - translation_param) * ref_point ) self._normalize_rvs() self.add_edge_vectors() ``` ##### interactive_adapt_4 ``` interactive_adapt_4(preferred_ranges: ndarray) -> None ``` Adapt reference vectors using the Decision maker's preferred range for each objective. Using these ranges, Latin hypercube sampling is applied to generate m number of samples between within these ranges, where m is the number of reference vectors. Normalized vectors constructed of these samples are then set as new reference vectors. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | -------------------------------------------------------------------------- | ---------- | | `preferred_ranges` | `ndarray` | Preferred lower and upper bound for each of the objective function values. | *required* | Source code in `desdeo/emo/operators/selection.py` ``` def interactive_adapt_4(self, preferred_ranges: np.ndarray) -> None: """Adapt reference vectors using the Decision maker's preferred range for each objective. Using these ranges, Latin hypercube sampling is applied to generate m number of samples between within these ranges, where m is the number of reference vectors. Normalized vectors constructed of these samples are then set as new reference vectors. Args: preferred_ranges (np.ndarray): Preferred lower and upper bound for each of the objective function values. """ # bounds lower_limits = np.min(preferred_ranges, axis=0) upper_limits = np.max(preferred_ranges, axis=0) # generate samples using Latin hypercube sampling lhs = LatinHypercube(d=self.num_dims, seed=self.rng) w = lhs.random(n=self.reference_vectors_initial.shape[0]) # scale between bounds w = w * (upper_limits - lower_limits) + lower_limits # set new reference vectors and normalize them self.reference_vectors = w self._normalize_rvs() self.add_edge_vectors() ``` #### BaseSelector Bases: `Subscriber` A base class for selection operators. Source code in `desdeo/emo/operators/selection.py` ``` class BaseSelector(Subscriber): """A base class for selection operators.""" def __init__(self, problem: Problem, verbosity: int, publisher: Publisher, seed: int = 0): """Initialize a selection operator.""" super().__init__(verbosity=verbosity, publisher=publisher) self.problem = problem self.variable_symbols = [x.symbol for x in problem.get_flattened_variables()] self.objective_symbols = [x.symbol for x in problem.objectives] self.maximization_mult = {x.symbol: -1 if x.maximize else 1 for x in problem.objectives} if problem.scalarization_funcs is None: self.target_symbols = [f"{x.symbol}_min" for x in problem.objectives] try: ideal, nadir = get_corrected_ideal_and_nadir(problem) # This is for the minimized problem self.ideal = np.array([ideal[x.symbol] for x in problem.objectives]) self.nadir = np.array([nadir[x.symbol] for x in problem.objectives]) if nadir is not None else None except ValueError: # in case the ideal and nadir are not provided self.ideal = None self.nadir = None else: self.target_symbols = [x.symbol for x in problem.scalarization_funcs if x.symbol is not None] self.ideal: np.ndarray | None = None self.nadir: np.ndarray | None = None if problem.constraints is None: self.constraints_symbols = None else: self.constraints_symbols = [x.symbol for x in problem.constraints] self.num_dims = len(self.target_symbols) self.seed = seed self.rng = np.random.default_rng(seed) @abstractmethod def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ ``` ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, seed: int = 0, ) ``` Initialize a selection operator. Source code in `desdeo/emo/operators/selection.py` ``` def __init__(self, problem: Problem, verbosity: int, publisher: Publisher, seed: int = 0): """Initialize a selection operator.""" super().__init__(verbosity=verbosity, publisher=publisher) self.problem = problem self.variable_symbols = [x.symbol for x in problem.get_flattened_variables()] self.objective_symbols = [x.symbol for x in problem.objectives] self.maximization_mult = {x.symbol: -1 if x.maximize else 1 for x in problem.objectives} if problem.scalarization_funcs is None: self.target_symbols = [f"{x.symbol}_min" for x in problem.objectives] try: ideal, nadir = get_corrected_ideal_and_nadir(problem) # This is for the minimized problem self.ideal = np.array([ideal[x.symbol] for x in problem.objectives]) self.nadir = np.array([nadir[x.symbol] for x in problem.objectives]) if nadir is not None else None except ValueError: # in case the ideal and nadir are not provided self.ideal = None self.nadir = None else: self.target_symbols = [x.symbol for x in problem.scalarization_funcs if x.symbol is not None] self.ideal: np.ndarray | None = None self.nadir: np.ndarray | None = None if problem.constraints is None: self.constraints_symbols = None else: self.constraints_symbols = [x.symbol for x in problem.constraints] self.num_dims = len(self.target_symbols) self.seed = seed self.rng = np.random.default_rng(seed) ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the selection operation. Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | Returns: | Type | Description | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: The selected decision variables and their objective values, targets, and constraint violations. | Source code in `desdeo/emo/operators/selection.py` ``` @abstractmethod def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ ``` #### HypESelector Bases: `_FitnessPublishingSelector` The environmental selection of HypE, and the hypervolume fitness for its mating selection. Parents and offspring are sorted into nondominated fronts, copied whole while they fit. From the front that does not fit, solutions are removed one at a time, each time the one with the smallest `I_h^k`, where `k` is the number still to be removed and the fitness is recomputed after every removal; ties are broken at random (Bader and Zitzler, Algorithm 7 and Section V). The fitness published for the binary tournament is `I_h^N(a, P, R)` over the selected population (Algorithm 6). The fitness is computed exactly up to `exact_max_objectives` objectives (three, as the paper recommends) and estimated from `n_samples` Monte Carlo samples above that. The paper leaves the reference point to the user. Here the objectives are normalized to [0, 1] by the minimum and maximum over parents and offspring each generation, as DESDEO's SMS-EMOA does, and the reference point is `normalised_reference_point_component` in every objective. On a constrained problem the fronts follow constrained domination (Deb et al. 2002), and the published fitness places every infeasible solution below every feasible one. This is DESDEO's addition. References Bader, J., & Zitzler, E. (2011). HypE: An algorithm for fast hypervolume-based many-objective optimization. Evolutionary Computation, 19(1), 45-76. https://doi.org/10.1162/EVCO_a_00009 (Implemented from the technical report version: Bader, J., & Zitzler, E. (2008). TIK Report 286, ETH Zurich. https://doi.org/10.3929/ethz-a-005703480) Source code in `desdeo/emo/operators/selection.py` ``` class HypESelector(_FitnessPublishingSelector): """The environmental selection of HypE, and the hypervolume fitness for its mating selection. Parents and offspring are sorted into nondominated fronts, copied whole while they fit. From the front that does not fit, solutions are removed one at a time, each time the one with the smallest `I_h^k`, where `k` is the number still to be removed and the fitness is recomputed after every removal; ties are broken at random (Bader and Zitzler, Algorithm 7 and Section V). The fitness published for the binary tournament is `I_h^N(a, P, R)` over the selected population (Algorithm 6). The fitness is computed exactly up to `exact_max_objectives` objectives (three, as the paper recommends) and estimated from `n_samples` Monte Carlo samples above that. The paper leaves the reference point to the user. Here the objectives are normalized to [0, 1] by the minimum and maximum over parents and offspring each generation, as DESDEO's SMS-EMOA does, and the reference point is `normalised_reference_point_component` in every objective. On a constrained problem the fronts follow constrained domination (Deb et al. 2002), and the published fitness places every infeasible solution below every feasible one. This is DESDEO's addition. References: Bader, J., & Zitzler, E. (2011). HypE: An algorithm for fast hypervolume-based many-objective optimization. Evolutionary Computation, 19(1), 45-76. https://doi.org/10.1162/EVCO_a_00009 (Implemented from the technical report version: Bader, J., & Zitzler, E. (2008). TIK Report 286, ETH Zurich. https://doi.org/10.3929/ethz-a-005703480) """ def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, population_size: int, n_samples: int = 10_000, exact_max_objectives: int = 3, normalised_reference_point_component: float = 1.1, seed: int = 0, ): """Initialize the HypE selector. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. population_size (int): The number of solutions selected each generation, `N`. n_samples (int, optional): The number of Monte Carlo samples `M`. Defaults to 10 000, the paper's. exact_max_objectives (int, optional): The most objectives for which the fitness is computed exactly, at most 3. Defaults to 3, as the paper recommends. normalised_reference_point_component (float, optional): The reference point in every normalized objective. Must exceed one. Defaults to 1.1. seed (int, optional): The random seed to use. Defaults to 0. """ raise NotImplementedError( """ HypESelector is not implemented yet. (I haven't checked the implementation fully yet.) Plus, it's very slow, and the behaviour is similar to IBEA. You aren't missing much. """ ) super().__init__(problem, verbosity=verbosity, publisher=publisher, population_size=population_size, seed=seed) if n_samples < 1: raise ValueError("n_samples must be positive.") if not 0 <= exact_max_objectives <= 3: # noqa: PLR2004 raise ValueError("exact_max_objectives must be between 0 and 3.") if normalised_reference_point_component <= 1: raise ValueError("normalised_reference_point_component must exceed one.") self.n_samples = n_samples self.exact_max_objectives = exact_max_objectives self.reference_point_component = normalised_reference_point_component def hypervolume_fitness(self, points: np.ndarray, k: int) -> np.ndarray: """`I_h^k` of every point against the normalized reference point, exact or estimated.""" reference = np.full(points.shape[1], self.reference_point_component) if 2 <= points.shape[1] <= self.exact_max_objectives: # noqa: PLR2004 return hype_fitness_exact(points, reference, k) return hype_fitness_monte_carlo(points, reference, k, self.n_samples, self.rng) def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Select the next population from parents and offspring. Args: parents (tuple[SolutionType, pl.DataFrame]): the parents and their outputs. offsprings (tuple[SolutionType, pl.DataFrame]): the offspring and their outputs. Empty in the first generation. Returns: tuple[SolutionType, pl.DataFrame]: the selected solutions and their outputs. """ solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy().astype(float) lower, upper = targets.min(axis=0), targets.max(axis=0) span = np.where(upper > lower, upper - lower, 1.0) normalized = (targets - lower) / span violations = total_constraint_violation(outputs, self.constraints_symbols) fronts = constrained_fronts(targets, violations) # Algorithm 7, lines 6-18: copy whole fronts while they fit. chosen: list[int] = [] last = np.array([], dtype=int) for front in fronts: members = np.flatnonzero(front) if len(chosen) + len(members) > self.population_size: last = members break chosen.extend(int(i) for i in members) # Lines 19-38: remove the worst of the last front one at a time, recomputing I_h^k each time. to_remove = len(chosen) + len(last) - self.population_size while to_remove > 0: fitness = self.hypervolume_fitness(normalized[last], to_remove) worst = np.flatnonzero(fitness == fitness.min()) last = np.delete(last, worst[0] if len(worst) == 1 else self.rng.choice(worst)) to_remove -= 1 chosen.extend(int(i) for i in last) # Algorithm 6: the mating fitness is I_h^N(a, P, R) over the new population. fitness = self.hypervolume_fitness(normalized[chosen], len(chosen)) if violations is not None: selected_violations = violations[chosen] infeasible = selected_violations > 0 if infeasible.all(): fitness = 1.0 / (1.0 + selected_violations) elif infeasible.any(): # Below every feasible solution, the least infeasible highest. floor = fitness[~infeasible].min() fitness[infeasible] = ( floor * 0.5 * (1.0 - selected_violations[infeasible] / (2.0 * selected_violations.max())) ) return self._finish(solutions, outputs, chosen, fitness) ``` ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, population_size: int, n_samples: int = 10000, exact_max_objectives: int = 3, normalised_reference_point_component: float = 1.1, seed: int = 0, ) ``` Initialize the HypE selector. Parameters: | Name | Type | Description | Default | | -------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The optimization problem to be solved. | *required* | | `verbosity` | `int` | The verbosity level of the operator. | *required* | | `publisher` | `Publisher` | The publisher to use for communication. | *required* | | `population_size` | `int` | The number of solutions selected each generation, N. | *required* | | `n_samples` | `int` | The number of Monte Carlo samples M. Defaults to 10 000, the paper's. | `10000` | | `exact_max_objectives` | `int` | The most objectives for which the fitness is computed exactly, at most 3. Defaults to 3, as the paper recommends. | `3` | | `normalised_reference_point_component` | `float` | The reference point in every normalized objective. Must exceed one. Defaults to 1.1. | `1.1` | | `seed` | `int` | The random seed to use. Defaults to 0. | `0` | Source code in `desdeo/emo/operators/selection.py` ``` def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, population_size: int, n_samples: int = 10_000, exact_max_objectives: int = 3, normalised_reference_point_component: float = 1.1, seed: int = 0, ): """Initialize the HypE selector. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. population_size (int): The number of solutions selected each generation, `N`. n_samples (int, optional): The number of Monte Carlo samples `M`. Defaults to 10 000, the paper's. exact_max_objectives (int, optional): The most objectives for which the fitness is computed exactly, at most 3. Defaults to 3, as the paper recommends. normalised_reference_point_component (float, optional): The reference point in every normalized objective. Must exceed one. Defaults to 1.1. seed (int, optional): The random seed to use. Defaults to 0. """ raise NotImplementedError( """ HypESelector is not implemented yet. (I haven't checked the implementation fully yet.) Plus, it's very slow, and the behaviour is similar to IBEA. You aren't missing much. """ ) super().__init__(problem, verbosity=verbosity, publisher=publisher, population_size=population_size, seed=seed) if n_samples < 1: raise ValueError("n_samples must be positive.") if not 0 <= exact_max_objectives <= 3: # noqa: PLR2004 raise ValueError("exact_max_objectives must be between 0 and 3.") if normalised_reference_point_component <= 1: raise ValueError("normalised_reference_point_component must exceed one.") self.n_samples = n_samples self.exact_max_objectives = exact_max_objectives self.reference_point_component = normalised_reference_point_component ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Select the next population from parents and offspring. Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | --------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | the parents and their outputs. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | the offspring and their outputs. Empty in the first generation. | *required* | Returns: | Type | Description | | -------------------------------- | ------------------------------------------------------------------------------ | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: the selected solutions and their outputs. | Source code in `desdeo/emo/operators/selection.py` ``` def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Select the next population from parents and offspring. Args: parents (tuple[SolutionType, pl.DataFrame]): the parents and their outputs. offsprings (tuple[SolutionType, pl.DataFrame]): the offspring and their outputs. Empty in the first generation. Returns: tuple[SolutionType, pl.DataFrame]: the selected solutions and their outputs. """ solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy().astype(float) lower, upper = targets.min(axis=0), targets.max(axis=0) span = np.where(upper > lower, upper - lower, 1.0) normalized = (targets - lower) / span violations = total_constraint_violation(outputs, self.constraints_symbols) fronts = constrained_fronts(targets, violations) # Algorithm 7, lines 6-18: copy whole fronts while they fit. chosen: list[int] = [] last = np.array([], dtype=int) for front in fronts: members = np.flatnonzero(front) if len(chosen) + len(members) > self.population_size: last = members break chosen.extend(int(i) for i in members) # Lines 19-38: remove the worst of the last front one at a time, recomputing I_h^k each time. to_remove = len(chosen) + len(last) - self.population_size while to_remove > 0: fitness = self.hypervolume_fitness(normalized[last], to_remove) worst = np.flatnonzero(fitness == fitness.min()) last = np.delete(last, worst[0] if len(worst) == 1 else self.rng.choice(worst)) to_remove -= 1 chosen.extend(int(i) for i in last) # Algorithm 6: the mating fitness is I_h^N(a, P, R) over the new population. fitness = self.hypervolume_fitness(normalized[chosen], len(chosen)) if violations is not None: selected_violations = violations[chosen] infeasible = selected_violations > 0 if infeasible.all(): fitness = 1.0 / (1.0 + selected_violations) elif infeasible.any(): # Below every feasible solution, the least infeasible highest. floor = fitness[~infeasible].min() fitness[infeasible] = ( floor * 0.5 * (1.0 - selected_violations[infeasible] / (2.0 * selected_violations.max())) ) return self._finish(solutions, outputs, chosen, fitness) ``` ##### hypervolume_fitness ``` hypervolume_fitness(points: ndarray, k: int) -> np.ndarray ``` `I_h^k` of every point against the normalized reference point, exact or estimated. Source code in `desdeo/emo/operators/selection.py` ``` def hypervolume_fitness(self, points: np.ndarray, k: int) -> np.ndarray: """`I_h^k` of every point against the normalized reference point, exact or estimated.""" reference = np.full(points.shape[1], self.reference_point_component) if 2 <= points.shape[1] <= self.exact_max_objectives: # noqa: PLR2004 return hype_fitness_exact(points, reference, k) return hype_fitness_monte_carlo(points, reference, k, self.n_samples, self.rng) ``` #### IBEASelector Bases: `_FitnessPublishingSelector` The adaptive IBEA selection operator. Constraints are handled feasibility-first, as in `NSGA3Selector`: while feasible solutions alone can fill the population the infeasible ones are discarded and the indicator selection runs unchanged, and while they cannot, every feasible solution survives and the remaining places go to the least infeasible. The binary indicator itself is left untouched, since it compares objective vectors and has no reading of an infeasible one. Reference: Zitzler, E., Künzli, S. (2004). Indicator-Based Selection in Multiobjective Search. In: Yao, X., et al. Parallel Problem Solving from Nature - PPSN VIII. PPSN 2004. Lecture Notes in Computer Science, vol 3242. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-30217-9_84 Source code in `desdeo/emo/operators/selection.py` ``` class IBEASelector(_FitnessPublishingSelector): """The adaptive IBEA selection operator. Constraints are handled feasibility-first, as in `NSGA3Selector`: while feasible solutions alone can fill the population the infeasible ones are discarded and the indicator selection runs unchanged, and while they cannot, every feasible solution survives and the remaining places go to the least infeasible. The binary indicator itself is left untouched, since it compares objective vectors and has no reading of an infeasible one. Reference: Zitzler, E., Künzli, S. (2004). Indicator-Based Selection in Multiobjective Search. In: Yao, X., et al. Parallel Problem Solving from Nature - PPSN VIII. PPSN 2004. Lecture Notes in Computer Science, vol 3242. Springer, Berlin, Heidelberg. https://doi.org/10.1007/978-3-540-30217-9_84 """ def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, population_size: int, kappa: float = 0.05, binary_indicator: Callable[[np.ndarray], np.ndarray] = self_epsilon, seed: int = 0, ): """Initialize the IBEA selector. Args: problem (Problem): The problem to solve. verbosity (int): The verbosity level of the selector. publisher (Publisher): The publisher to send messages to. population_size (int): The size of the population to select. kappa (float, optional): The kappa value for the IBEA selection. Defaults to 0.05. binary_indicator (Callable[[np.ndarray], np.ndarray], optional): The binary indicator function to use. Defaults to self_epsilon with uses binary addaptive epsilon indicator. seed (int, optional): The random seed to use. Defaults to 0. """ # TODO(@light-weaver): IBEA doesn't perform as good as expected # The distribution of solutions found isn't very uniform # Update 21st August, tested against jmetalpy IBEA. Our version is both faster and better # What is happening??? # Results are similar to this https://github.com/Xavier-MaYiMing/IBEA/ super().__init__( problem=problem, verbosity=verbosity, publisher=publisher, population_size=population_size, seed=seed ) self.binary_indicator = binary_indicator self.kappa = kappa def _indicator_components(self, targets: np.ndarray) -> np.ndarray: """Scale the targets to the unit box and return the pairwise binary indicator matrix.""" target_min = np.min(targets, axis=0) target_max = np.max(targets, axis=0) span = target_max - target_min # A target that is constant across the population carries no information; dividing by its # zero span would turn the whole indicator matrix into NaN. span[span == 0] = 1.0 return self.binary_indicator((targets - target_min) / span) def _adaptive_kappa(self, components: np.ndarray) -> float: """Adaptive IBEA's kappa: the configured kappa scaled by the largest indicator magnitude. The scaling makes kappa independent of the objectives' range. When the set has collapsed onto a single objective vector every indicator value is zero, and so is the scale: dividing by it raised ZeroDivisionError in the fitness kernels and would turn the vectorised survivor selection into NaN. A set with no spread has nothing to scale, so the configured kappa is used unscaled. Every exp(-0 / kappa) is then 1 and each member's fitness is -(n - 1), a tie, which is the honest reading of a set the indicator cannot separate. Wherever the scale is positive the value is exactly what it was before. """ scale = float(np.abs(components).max()) return self.kappa * scale if scale > 0 else self.kappa def _infeasible_fitness(self, targets: np.ndarray, violations: np.ndarray) -> np.ndarray: """Fitness for a set that is partly or wholly infeasible, feasible solutions first. The binary indicator only orders solutions sensibly when they are all feasible, so the indicator fitness is kept for the feasible members and every infeasible member is placed strictly below all of them, ordered among themselves by total violation. Fitness stays higher-is-better, which is what the mating tournament expects. """ components = self._indicator_components(targets) fitness = _ibea_fitness(components, kappa=self._adaptive_kappa(components)) infeasible = violations > 0 if not np.any(infeasible): return fitness feasible_worst = fitness[~infeasible].min() if np.any(~infeasible) else 0.0 fitness[infeasible] = feasible_worst - violations[infeasible] / violations[infeasible].max() return fitness def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ # A population seeded with fewer solutions than population_size keeps all of them and their offspring # until it is full: _ibea_select_all removes no one then. Fitness is published either way, as the mating # selection that follows needs it. solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy() violations = total_constraint_violation(outputs, self.constraints_symbols) if violations is None: candidates = np.arange(len(outputs)) else: candidates = np.flatnonzero(violations <= 0) if len(candidates) <= self.population_size: # Too few feasible solutions to fill the population, so the indicator has nothing to # choose between: keep every feasible solution and top up with the least infeasible. chosen = np.argsort(violations, kind="stable")[: self.population_size] fitness = self._infeasible_fitness(targets[chosen], violations[chosen]) return self._finish(solutions, outputs, chosen.tolist(), fitness) # Enough feasible solutions to fill the population, so the infeasible ones are simply # dropped and the indicator selection proceeds unchanged on the feasible ones. # Adaptation components = self._indicator_components(targets[candidates]) survivors = _ibea_select_all( components, population_size=self.population_size, kappa=self._adaptive_kappa(components) ) components = components[survivors][:, survivors] fitness = _ibea_fitness(components, kappa=self._adaptive_kappa(components)) return self._finish(solutions, outputs, candidates[survivors].tolist(), fitness) ``` ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, population_size: int, kappa: float = 0.05, binary_indicator: Callable[ [ndarray], ndarray ] = self_epsilon, seed: int = 0, ) ``` Initialize the IBEA selector. Parameters: | Name | Type | Description | Default | | ------------------ | ------------------------------ | ------------------------------------------------------------------------------------------------------------ | -------------- | | `problem` | `Problem` | The problem to solve. | *required* | | `verbosity` | `int` | The verbosity level of the selector. | *required* | | `publisher` | `Publisher` | The publisher to send messages to. | *required* | | `population_size` | `int` | The size of the population to select. | *required* | | `kappa` | `float` | The kappa value for the IBEA selection. Defaults to 0.05. | `0.05` | | `binary_indicator` | `Callable[[ndarray], ndarray]` | The binary indicator function to use. Defaults to self_epsilon with uses binary addaptive epsilon indicator. | `self_epsilon` | | `seed` | `int` | The random seed to use. Defaults to 0. | `0` | Source code in `desdeo/emo/operators/selection.py` ``` def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, population_size: int, kappa: float = 0.05, binary_indicator: Callable[[np.ndarray], np.ndarray] = self_epsilon, seed: int = 0, ): """Initialize the IBEA selector. Args: problem (Problem): The problem to solve. verbosity (int): The verbosity level of the selector. publisher (Publisher): The publisher to send messages to. population_size (int): The size of the population to select. kappa (float, optional): The kappa value for the IBEA selection. Defaults to 0.05. binary_indicator (Callable[[np.ndarray], np.ndarray], optional): The binary indicator function to use. Defaults to self_epsilon with uses binary addaptive epsilon indicator. seed (int, optional): The random seed to use. Defaults to 0. """ # TODO(@light-weaver): IBEA doesn't perform as good as expected # The distribution of solutions found isn't very uniform # Update 21st August, tested against jmetalpy IBEA. Our version is both faster and better # What is happening??? # Results are similar to this https://github.com/Xavier-MaYiMing/IBEA/ super().__init__( problem=problem, verbosity=verbosity, publisher=publisher, population_size=population_size, seed=seed ) self.binary_indicator = binary_indicator self.kappa = kappa ``` ##### \_adaptive_kappa ``` _adaptive_kappa(components: ndarray) -> float ``` Adaptive IBEA's kappa: the configured kappa scaled by the largest indicator magnitude. The scaling makes kappa independent of the objectives' range. When the set has collapsed onto a single objective vector every indicator value is zero, and so is the scale: dividing by it raised ZeroDivisionError in the fitness kernels and would turn the vectorised survivor selection into NaN. A set with no spread has nothing to scale, so the configured kappa is used unscaled. Every exp(-0 / kappa) is then 1 and each member's fitness is -(n - 1), a tie, which is the honest reading of a set the indicator cannot separate. Wherever the scale is positive the value is exactly what it was before. Source code in `desdeo/emo/operators/selection.py` ``` def _adaptive_kappa(self, components: np.ndarray) -> float: """Adaptive IBEA's kappa: the configured kappa scaled by the largest indicator magnitude. The scaling makes kappa independent of the objectives' range. When the set has collapsed onto a single objective vector every indicator value is zero, and so is the scale: dividing by it raised ZeroDivisionError in the fitness kernels and would turn the vectorised survivor selection into NaN. A set with no spread has nothing to scale, so the configured kappa is used unscaled. Every exp(-0 / kappa) is then 1 and each member's fitness is -(n - 1), a tie, which is the honest reading of a set the indicator cannot separate. Wherever the scale is positive the value is exactly what it was before. """ scale = float(np.abs(components).max()) return self.kappa * scale if scale > 0 else self.kappa ``` ##### \_indicator_components ``` _indicator_components(targets: ndarray) -> np.ndarray ``` Scale the targets to the unit box and return the pairwise binary indicator matrix. Source code in `desdeo/emo/operators/selection.py` ``` def _indicator_components(self, targets: np.ndarray) -> np.ndarray: """Scale the targets to the unit box and return the pairwise binary indicator matrix.""" target_min = np.min(targets, axis=0) target_max = np.max(targets, axis=0) span = target_max - target_min # A target that is constant across the population carries no information; dividing by its # zero span would turn the whole indicator matrix into NaN. span[span == 0] = 1.0 return self.binary_indicator((targets - target_min) / span) ``` ##### \_infeasible_fitness ``` _infeasible_fitness( targets: ndarray, violations: ndarray ) -> np.ndarray ``` Fitness for a set that is partly or wholly infeasible, feasible solutions first. The binary indicator only orders solutions sensibly when they are all feasible, so the indicator fitness is kept for the feasible members and every infeasible member is placed strictly below all of them, ordered among themselves by total violation. Fitness stays higher-is-better, which is what the mating tournament expects. Source code in `desdeo/emo/operators/selection.py` ``` def _infeasible_fitness(self, targets: np.ndarray, violations: np.ndarray) -> np.ndarray: """Fitness for a set that is partly or wholly infeasible, feasible solutions first. The binary indicator only orders solutions sensibly when they are all feasible, so the indicator fitness is kept for the feasible members and every infeasible member is placed strictly below all of them, ordered among themselves by total violation. Fitness stays higher-is-better, which is what the mating tournament expects. """ components = self._indicator_components(targets) fitness = _ibea_fitness(components, kappa=self._adaptive_kappa(components)) infeasible = violations > 0 if not np.any(infeasible): return fitness feasible_worst = fitness[~infeasible].min() if np.any(~infeasible) else 0.0 fitness[infeasible] = feasible_worst - violations[infeasible] / violations[infeasible].max() return fitness ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the selection operation. Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | Returns: | Type | Description | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: The selected decision variables and their objective values, targets, and constraint violations. | Source code in `desdeo/emo/operators/selection.py` ``` def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ # A population seeded with fewer solutions than population_size keeps all of them and their offspring # until it is full: _ibea_select_all removes no one then. Fitness is published either way, as the mating # selection that follows needs it. solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy() violations = total_constraint_violation(outputs, self.constraints_symbols) if violations is None: candidates = np.arange(len(outputs)) else: candidates = np.flatnonzero(violations <= 0) if len(candidates) <= self.population_size: # Too few feasible solutions to fill the population, so the indicator has nothing to # choose between: keep every feasible solution and top up with the least infeasible. chosen = np.argsort(violations, kind="stable")[: self.population_size] fitness = self._infeasible_fitness(targets[chosen], violations[chosen]) return self._finish(solutions, outputs, chosen.tolist(), fitness) # Enough feasible solutions to fill the population, so the infeasible ones are simply # dropped and the indicator selection proceeds unchanged on the feasible ones. # Adaptation components = self._indicator_components(targets[candidates]) survivors = _ibea_select_all( components, population_size=self.population_size, kappa=self._adaptive_kappa(components) ) components = components[survivors][:, survivors] fitness = _ibea_fitness(components, kappa=self._adaptive_kappa(components)) return self._finish(solutions, outputs, candidates[survivors].tolist(), fitness) ``` #### MOEADSelector Bases: `BaseDecompositionSelector` The neighbourhood replacement of MOEA/D and MOEA/D-DE. MOEA/D keeps one solution per weight vector (subproblem). Each offspring is produced for one subproblem `i` from parents in its mating pool, and then replaces the current solution of every subproblem `j` in that pool whose aggregation value it matches or improves, `g(y | w_j, z) <= g(x_j | w_j, z)`. The pool is the neighbourhood `B(i)`, the `T` subproblems with the closest weight vectors, with probability `delta`, and the whole population otherwise. MOEA/D-DE visits the pool in random order and stops after `n_r` replacements, so that one good offspring cannot take over a whole neighbourhood. The original MOEA/D is `delta = 1` with no cap. Unlike the other selectors this one is driven one offspring at a time by template_moead: the template asks for the mating pool of subproblem `i` with `mating_pool(i)`, evaluates one offspring, and passes it to `do`, which updates the pool `mating_pool` returned. The first call to `do`, with no offspring, takes the initial population, one solution per subproblem in order, and sets the ideal point from it. The selector publishes its state when the template calls `notify`, once per generation, rather than on every replacement. Neither paper handles constraints. On a constrained problem the replacement compares total constraint violation first, so a solution with a smaller violation always replaces one with a larger violation, and the aggregation value decides only between equal violations, which for an unconstrained problem is every comparison. This is DESDEO's addition. A preference (reference point, preferred or non-preferred solutions, preferred ranges) adapts the weight vectors as in the other decomposition selectors (Hakanen et al. 2016). Those adaptations treat a vector as a direction in objective space. PBI reads it that way, but a Tchebycheff subproblem's optimum lies along `1 / w`, so with a preference the Tchebycheff weights are the WS-transformation (Qi et al. 2014) of the adapted vectors. The weighted sum has no direction to adapt and rejects preferences. References Zhang, Q., & Li, H. (2007). MOEA/D: A multiobjective evolutionary algorithm based on decomposition. IEEE Transactions on Evolutionary Computation, 11(6), 712-731. https://doi.org/10.1109/TEVC.2007.892759 Li, H., & Zhang, Q. (2009). Multiobjective optimization problems with complicated Pareto sets, MOEA/D and NSGA-II. IEEE Transactions on Evolutionary Computation, 13(2), 284-302. https://doi.org/10.1109/TEVC.2008.925798 Qi, Y., Ma, X., Liu, F., Jiao, L., Sun, J., & Wu, J. (2014). MOEA/D with adaptive weight adjustment. Evolutionary Computation, 22(2), 231-264. https://doi.org/10.1162/EVCO_a_00109 (The WS-transformation used with preferences.) Source code in `desdeo/emo/operators/selection.py` ``` class MOEADSelector(BaseDecompositionSelector): """The neighbourhood replacement of MOEA/D and MOEA/D-DE. MOEA/D keeps one solution per weight vector (subproblem). Each offspring is produced for one subproblem `i` from parents in its mating pool, and then replaces the current solution of every subproblem `j` in that pool whose aggregation value it matches or improves, `g(y | w_j, z) <= g(x_j | w_j, z)`. The pool is the neighbourhood `B(i)`, the `T` subproblems with the closest weight vectors, with probability `delta`, and the whole population otherwise. MOEA/D-DE visits the pool in random order and stops after `n_r` replacements, so that one good offspring cannot take over a whole neighbourhood. The original MOEA/D is `delta = 1` with no cap. Unlike the other selectors this one is driven one offspring at a time by [template_moead][desdeo.emo.methods.templates.template_moead]: the template asks for the mating pool of subproblem `i` with `mating_pool(i)`, evaluates one offspring, and passes it to `do`, which updates the pool `mating_pool` returned. The first call to `do`, with no offspring, takes the initial population, one solution per subproblem in order, and sets the ideal point from it. The selector publishes its state when the template calls `notify`, once per generation, rather than on every replacement. Neither paper handles constraints. On a constrained problem the replacement compares total constraint violation first, so a solution with a smaller violation always replaces one with a larger violation, and the aggregation value decides only between equal violations, which for an unconstrained problem is every comparison. This is DESDEO's addition. A preference (reference point, preferred or non-preferred solutions, preferred ranges) adapts the weight vectors as in the other decomposition selectors (Hakanen et al. 2016). Those adaptations treat a vector as a direction in objective space. PBI reads it that way, but a Tchebycheff subproblem's optimum lies along `1 / w`, so with a preference the Tchebycheff weights are the WS-transformation (Qi et al. 2014) of the adapted vectors. The weighted sum has no direction to adapt and rejects preferences. References: Zhang, Q., & Li, H. (2007). MOEA/D: A multiobjective evolutionary algorithm based on decomposition. IEEE Transactions on Evolutionary Computation, 11(6), 712-731. https://doi.org/10.1109/TEVC.2007.892759 Li, H., & Zhang, Q. (2009). Multiobjective optimization problems with complicated Pareto sets, MOEA/D and NSGA-II. IEEE Transactions on Evolutionary Computation, 13(2), 284-302. https://doi.org/10.1109/TEVC.2008.925798 Qi, Y., Ma, X., Liu, F., Jiao, L., Sun, J., & Wu, J. (2014). MOEA/D with adaptive weight adjustment. Evolutionary Computation, 22(2), 231-264. https://doi.org/10.1162/EVCO_a_00109 (The WS-transformation used with preferences.) """ @property def provided_topics(self): """The message topics this operator publishes, keyed by verbosity level.""" return { 0: [], 1: [SelectorMessageTopics.STATE], 2: [ SelectorMessageTopics.REFERENCE_VECTORS, SelectorMessageTopics.STATE, SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, ], } @property def interested_topics(self): """The message topics this operator subscribes to.""" return [] def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, reference_vector_options: ReferenceVectorOptions | dict | None = None, neighbourhood_size: int = 20, neighbourhood_probability: float = 1.0, max_replacements: int | None = None, aggregation: Literal["tchebycheff", "pbi", "weighted_sum"] = "tchebycheff", pbi_penalty: float = 5.0, seed: int = 0, ): """Initialize the MOEA/D selector. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. reference_vector_options (ReferenceVectorOptions | dict | None, optional): Options for the weight vectors. The vectors are always normalized to sum to one. Defaults to None, which uses the default `ReferenceVectorOptions`. neighbourhood_size (int, optional): The neighbourhood size `T`, counting the subproblem itself. Capped at the number of subproblems. Defaults to 20. neighbourhood_probability (float, optional): The probability `delta` that the mating pool and the replacement range are the neighbourhood rather than the whole population. Defaults to 1.0, the original MOEA/D. max_replacements (int | None, optional): The maximum number `n_r` of solutions one offspring may replace. None, the default, places no cap, as in the original MOEA/D. aggregation (str, optional): The aggregation function, "tchebycheff", "pbi" or "weighted_sum". Defaults to "tchebycheff". pbi_penalty (float, optional): The penalty `theta` of the PBI function. Defaults to 5.0, the value of Zhang and Li (2007), Section V-G. seed (int, optional): The random seed to use. Defaults to 0. """ raise NotImplementedError(""" MOEADSelector is not yet implemented. I just haven't gotten around to checking the details of the implementation and testing it. It is very slow anyway, I wouldn't recommend using it for anything unless the objective functions are very expensive and cannot be evaluated in parallel. """) if reference_vector_options is None: reference_vector_options = ReferenceVectorOptions() elif isinstance(reference_vector_options, dict): reference_vector_options = ReferenceVectorOptions.model_validate(reference_vector_options) # MOEA/D's weight vectors are convex combinations of the objectives. reference_vector_options.vector_type = "planar" super().__init__( problem, reference_vector_options=reference_vector_options, verbosity=verbosity, publisher=publisher, seed=seed, ) if neighbourhood_size < 2: # noqa: PLR2004 raise ValueError("neighbourhood_size must be at least 2, the subproblem and one neighbour.") if not 0 <= neighbourhood_probability <= 1: raise ValueError("neighbourhood_probability must be in [0, 1].") if max_replacements is not None and max_replacements < 1: raise ValueError("max_replacements must be positive, or None for no cap.") if aggregation not in ("tchebycheff", "pbi", "weighted_sum"): raise ValueError(f"Unknown MOEA/D aggregation function: {aggregation}") self.weights = self.reference_vectors options = self.reference_vector_options if ( options.reference_point or options.preferred_solutions or options.non_preferred_solutions or (options.preferred_ranges) ): # The preference adaptations of Hakanen et al. (2016) place the vectors as directions in # objective space, which is how PBI reads a weight vector. The optimum of a Tchebycheff # subproblem lies along 1 / w instead, so the adapted vectors go through the # WS-transformation of Qi et al. (2014), Eq. 3, whose Tchebycheff optimum lies along the # vector; a vector with a zero component is shifted by epsilon first, as in their # Algorithm 1, Step 2. Without the transformation the population settles on the opposite # side of the front: on DTLZ2 with reference point (0.2, 0.5, 0.8), the median angle to # the reference direction was 44 degrees, against 5.5 with it (6 for PBI). if aggregation == "weighted_sum": raise ValueError("Preference handling is not supported with the weighted sum aggregation.") if aggregation == "tchebycheff": shifted = self.reference_vectors + 1e-6 * np.any(self.reference_vectors <= 0, axis=1, keepdims=True) inverse = 1.0 / shifted self.weights = inverse / inverse.sum(axis=1, keepdims=True) self.neighbourhood_size = min(neighbourhood_size, self.number_of_subproblems) self.neighbourhood_probability = neighbourhood_probability self.max_replacements = max_replacements self.aggregation = aggregation self.pbi_penalty = pbi_penalty # Step 1.1 (2009) / Step 1.2 (2007): the T closest weight vectors to each weight vector. A # subproblem's own vector is placed first explicitly, since preference handling can add edge # vectors that duplicate one already in the set. distances = cdist(self.weights, self.weights) np.fill_diagonal(distances, -1.0) self.neighbourhoods = np.argsort(distances, axis=1, kind="stable")[:, : self.neighbourhood_size] self.ideal_point: np.ndarray | None = None self.solutions: pl.DataFrame | None = None self.outputs: pl.DataFrame | None = None self._variables: np.ndarray | None = None self._outputs: np.ndarray | None = None self._targets: np.ndarray | None = None self._violations: np.ndarray | None = None self._subproblem: int | None = None self._pool: np.ndarray | None = None self.replaced: list[int] = [] @property def number_of_subproblems(self) -> int: """The number of subproblems, which is also the population size.""" return self.reference_vectors.shape[0] def mating_pool(self, subproblem: int) -> np.ndarray: """Draw the mating pool of a subproblem, which is also the range the offspring may replace in. This is Step 2.1 of MOEA/D-DE. With `neighbourhood_probability = 1` it is always the neighbourhood, as in the original MOEA/D. The pool is remembered for the next call to `do`. Args: subproblem (int): The index `i` of the subproblem an offspring is about to be made for. Returns: np.ndarray: The indices of the subproblems in the pool. Always contains `subproblem`. """ if self.rng.random() < self.neighbourhood_probability: pool = self.neighbourhoods[subproblem] else: pool = np.arange(self.number_of_subproblems) self._subproblem = subproblem self._pool = pool return pool def _aggregate(self, targets: np.ndarray, subproblems: np.ndarray) -> np.ndarray: return moead_scalarize( targets, self.weights[subproblems], self.ideal_point, self.aggregation, pbi_penalty=self.pbi_penalty ) def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Initialize the population, or update the last mating pool with one or more offspring. Args: parents (tuple[SolutionType, pl.DataFrame]): The current population, one solution per subproblem in order, and its outputs. offsprings (tuple[SolutionType, pl.DataFrame]): The offspring and their outputs. Empty on the first call, which takes `parents` as the initial population. Returns: tuple[SolutionType, pl.DataFrame]: The updated population and its outputs. Raises: ValueError: If the initial population does not hold one solution per subproblem, or if offspring arrive before `mating_pool` has been called. """ if not isinstance(parents[0], pl.DataFrame): raise TypeError("MOEADSelector works on polars DataFrames only.") if offsprings[1].is_empty(): return self._initialize(parents[0], parents[1]) if self._pool is None: raise ValueError("Call mating_pool(i) for the subproblem before passing its offspring to do().") offspring_targets = offsprings[1][self.target_symbols].to_numpy() offspring_violations = total_constraint_violation(offsprings[1], self.constraints_symbols) offspring_variables = offsprings[0][self.variable_symbols].to_numpy() offspring_outputs = offsprings[1][self.outputs.columns].to_numpy() self.replaced = [] for row in range(offspring_targets.shape[0]): y = offspring_targets[row] y_violation = 0.0 if offspring_violations is None else offspring_violations[row] # 2007 Step 2.3 / 2009 Step 2.4: update the ideal point. self.ideal_point = np.minimum(self.ideal_point, y) # 2009 Step 2.5: visit the pool in random order and stop after n_r replacements. With # no cap, the order does not matter and this is 2007 Step 2.4. order = self.rng.permutation(self._pool) g_new = self._aggregate(np.broadcast_to(y, (len(order), len(y))), order) g_old = self._aggregate(self._targets[order], order) old_violations = self._violations[order] better = (y_violation < old_violations) | ((y_violation == old_violations) & (g_new <= g_old)) winners = order[better] if self.max_replacements is not None: winners = winners[: self.max_replacements] self._variables[winners] = offspring_variables[row] self._outputs[winners] = offspring_outputs[row] self._targets[winners] = y self._violations[winners] = y_violation self.replaced.extend(winners.tolist()) if self.replaced: self.solutions = pl.DataFrame(self._variables, schema=self.solutions.schema, orient="row") self.outputs = pl.DataFrame(self._outputs, schema=self.outputs.schema, orient="row") return self.solutions, self.outputs def _initialize(self, solutions: pl.DataFrame, outputs: pl.DataFrame) -> tuple[pl.DataFrame, pl.DataFrame]: """Take the initial population and set the ideal point from it (2007 Step 1.4, 2009 Step 1.3).""" if len(solutions) != self.number_of_subproblems: raise ValueError( f"MOEA/D needs one initial solution per subproblem: got {len(solutions)} solutions for " f"{self.number_of_subproblems} weight vectors." ) self.solutions = solutions[self.variable_symbols] self.outputs = outputs self._variables = self.solutions.to_numpy().astype(float) self._outputs = outputs.to_numpy().astype(float) self._targets = outputs[self.target_symbols].to_numpy().astype(float) violations = total_constraint_violation(outputs, self.constraints_symbols) self._violations = np.zeros(len(outputs)) if violations is None else violations.astype(float) self.ideal_point = self._targets.min(axis=0) self._pool = None self.notify() return self.solutions, self.outputs def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.solutions is None: return [] state = DictMessage( topic=SelectorMessageTopics.STATE, value={ "population_size": self.number_of_subproblems, "ideal_point": self.ideal_point.tolist(), }, source=self.__class__.__name__, ) if self.verbosity == 1: return [state] return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), state, PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.solutions.hstack(self.outputs), source=self.__class__.__name__, ), ] def update(self, message: Message) -> None: """Handle an incoming message. This operator does not react to messages.""" ``` ##### interested_topics ``` interested_topics ``` The message topics this operator subscribes to. ##### number_of_subproblems ``` number_of_subproblems: int ``` The number of subproblems, which is also the population size. ##### provided_topics ``` provided_topics ``` The message topics this operator publishes, keyed by verbosity level. ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, reference_vector_options: ReferenceVectorOptions | dict | None = None, neighbourhood_size: int = 20, neighbourhood_probability: float = 1.0, max_replacements: int | None = None, aggregation: Literal[ "tchebycheff", "pbi", "weighted_sum" ] = "tchebycheff", pbi_penalty: float = 5.0, seed: int = 0, ) ``` Initialize the MOEA/D selector. Parameters: | Name | Type | Description | Default | | --------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | The optimization problem to be solved. | *required* | | `verbosity` | `int` | The verbosity level of the operator. | *required* | | `publisher` | `Publisher` | The publisher to use for communication. | *required* | | `reference_vector_options` | \`ReferenceVectorOptions | dict | None\` | | `neighbourhood_size` | `int` | The neighbourhood size T, counting the subproblem itself. Capped at the number of subproblems. Defaults to 20. | `20` | | `neighbourhood_probability` | `float` | The probability delta that the mating pool and the replacement range are the neighbourhood rather than the whole population. Defaults to 1.0, the original MOEA/D. | `1.0` | | `max_replacements` | \`int | None\` | The maximum number n_r of solutions one offspring may replace. None, the default, places no cap, as in the original MOEA/D. | | `aggregation` | `str` | The aggregation function, "tchebycheff", "pbi" or "weighted_sum". Defaults to "tchebycheff". | `'tchebycheff'` | | `pbi_penalty` | `float` | The penalty theta of the PBI function. Defaults to 5.0, the value of Zhang and Li (2007), Section V-G. | `5.0` | | `seed` | `int` | The random seed to use. Defaults to 0. | `0` | Source code in `desdeo/emo/operators/selection.py` ``` def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, reference_vector_options: ReferenceVectorOptions | dict | None = None, neighbourhood_size: int = 20, neighbourhood_probability: float = 1.0, max_replacements: int | None = None, aggregation: Literal["tchebycheff", "pbi", "weighted_sum"] = "tchebycheff", pbi_penalty: float = 5.0, seed: int = 0, ): """Initialize the MOEA/D selector. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. reference_vector_options (ReferenceVectorOptions | dict | None, optional): Options for the weight vectors. The vectors are always normalized to sum to one. Defaults to None, which uses the default `ReferenceVectorOptions`. neighbourhood_size (int, optional): The neighbourhood size `T`, counting the subproblem itself. Capped at the number of subproblems. Defaults to 20. neighbourhood_probability (float, optional): The probability `delta` that the mating pool and the replacement range are the neighbourhood rather than the whole population. Defaults to 1.0, the original MOEA/D. max_replacements (int | None, optional): The maximum number `n_r` of solutions one offspring may replace. None, the default, places no cap, as in the original MOEA/D. aggregation (str, optional): The aggregation function, "tchebycheff", "pbi" or "weighted_sum". Defaults to "tchebycheff". pbi_penalty (float, optional): The penalty `theta` of the PBI function. Defaults to 5.0, the value of Zhang and Li (2007), Section V-G. seed (int, optional): The random seed to use. Defaults to 0. """ raise NotImplementedError(""" MOEADSelector is not yet implemented. I just haven't gotten around to checking the details of the implementation and testing it. It is very slow anyway, I wouldn't recommend using it for anything unless the objective functions are very expensive and cannot be evaluated in parallel. """) if reference_vector_options is None: reference_vector_options = ReferenceVectorOptions() elif isinstance(reference_vector_options, dict): reference_vector_options = ReferenceVectorOptions.model_validate(reference_vector_options) # MOEA/D's weight vectors are convex combinations of the objectives. reference_vector_options.vector_type = "planar" super().__init__( problem, reference_vector_options=reference_vector_options, verbosity=verbosity, publisher=publisher, seed=seed, ) if neighbourhood_size < 2: # noqa: PLR2004 raise ValueError("neighbourhood_size must be at least 2, the subproblem and one neighbour.") if not 0 <= neighbourhood_probability <= 1: raise ValueError("neighbourhood_probability must be in [0, 1].") if max_replacements is not None and max_replacements < 1: raise ValueError("max_replacements must be positive, or None for no cap.") if aggregation not in ("tchebycheff", "pbi", "weighted_sum"): raise ValueError(f"Unknown MOEA/D aggregation function: {aggregation}") self.weights = self.reference_vectors options = self.reference_vector_options if ( options.reference_point or options.preferred_solutions or options.non_preferred_solutions or (options.preferred_ranges) ): # The preference adaptations of Hakanen et al. (2016) place the vectors as directions in # objective space, which is how PBI reads a weight vector. The optimum of a Tchebycheff # subproblem lies along 1 / w instead, so the adapted vectors go through the # WS-transformation of Qi et al. (2014), Eq. 3, whose Tchebycheff optimum lies along the # vector; a vector with a zero component is shifted by epsilon first, as in their # Algorithm 1, Step 2. Without the transformation the population settles on the opposite # side of the front: on DTLZ2 with reference point (0.2, 0.5, 0.8), the median angle to # the reference direction was 44 degrees, against 5.5 with it (6 for PBI). if aggregation == "weighted_sum": raise ValueError("Preference handling is not supported with the weighted sum aggregation.") if aggregation == "tchebycheff": shifted = self.reference_vectors + 1e-6 * np.any(self.reference_vectors <= 0, axis=1, keepdims=True) inverse = 1.0 / shifted self.weights = inverse / inverse.sum(axis=1, keepdims=True) self.neighbourhood_size = min(neighbourhood_size, self.number_of_subproblems) self.neighbourhood_probability = neighbourhood_probability self.max_replacements = max_replacements self.aggregation = aggregation self.pbi_penalty = pbi_penalty # Step 1.1 (2009) / Step 1.2 (2007): the T closest weight vectors to each weight vector. A # subproblem's own vector is placed first explicitly, since preference handling can add edge # vectors that duplicate one already in the set. distances = cdist(self.weights, self.weights) np.fill_diagonal(distances, -1.0) self.neighbourhoods = np.argsort(distances, axis=1, kind="stable")[:, : self.neighbourhood_size] self.ideal_point: np.ndarray | None = None self.solutions: pl.DataFrame | None = None self.outputs: pl.DataFrame | None = None self._variables: np.ndarray | None = None self._outputs: np.ndarray | None = None self._targets: np.ndarray | None = None self._violations: np.ndarray | None = None self._subproblem: int | None = None self._pool: np.ndarray | None = None self.replaced: list[int] = [] ``` ##### \_initialize ``` _initialize( solutions: DataFrame, outputs: DataFrame ) -> tuple[pl.DataFrame, pl.DataFrame] ``` Take the initial population and set the ideal point from it (2007 Step 1.4, 2009 Step 1.3). Source code in `desdeo/emo/operators/selection.py` ``` def _initialize(self, solutions: pl.DataFrame, outputs: pl.DataFrame) -> tuple[pl.DataFrame, pl.DataFrame]: """Take the initial population and set the ideal point from it (2007 Step 1.4, 2009 Step 1.3).""" if len(solutions) != self.number_of_subproblems: raise ValueError( f"MOEA/D needs one initial solution per subproblem: got {len(solutions)} solutions for " f"{self.number_of_subproblems} weight vectors." ) self.solutions = solutions[self.variable_symbols] self.outputs = outputs self._variables = self.solutions.to_numpy().astype(float) self._outputs = outputs.to_numpy().astype(float) self._targets = outputs[self.target_symbols].to_numpy().astype(float) violations = total_constraint_violation(outputs, self.constraints_symbols) self._violations = np.zeros(len(outputs)) if violations is None else violations.astype(float) self.ideal_point = self._targets.min(axis=0) self._pool = None self.notify() return self.solutions, self.outputs ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Initialize the population, or update the last mating pool with one or more offspring. Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | -------------------------------------------------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | The current population, one solution per subproblem in order, and its outputs. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | The offspring and their outputs. Empty on the first call, which takes parents as the initial population. | *required* | Returns: | Type | Description | | -------------------------------- | ---------------------------------------------------------------------------- | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: The updated population and its outputs. | Raises: | Type | Description | | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | | `ValueError` | If the initial population does not hold one solution per subproblem, or if offspring arrive before mating_pool has been called. | Source code in `desdeo/emo/operators/selection.py` ``` def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Initialize the population, or update the last mating pool with one or more offspring. Args: parents (tuple[SolutionType, pl.DataFrame]): The current population, one solution per subproblem in order, and its outputs. offsprings (tuple[SolutionType, pl.DataFrame]): The offspring and their outputs. Empty on the first call, which takes `parents` as the initial population. Returns: tuple[SolutionType, pl.DataFrame]: The updated population and its outputs. Raises: ValueError: If the initial population does not hold one solution per subproblem, or if offspring arrive before `mating_pool` has been called. """ if not isinstance(parents[0], pl.DataFrame): raise TypeError("MOEADSelector works on polars DataFrames only.") if offsprings[1].is_empty(): return self._initialize(parents[0], parents[1]) if self._pool is None: raise ValueError("Call mating_pool(i) for the subproblem before passing its offspring to do().") offspring_targets = offsprings[1][self.target_symbols].to_numpy() offspring_violations = total_constraint_violation(offsprings[1], self.constraints_symbols) offspring_variables = offsprings[0][self.variable_symbols].to_numpy() offspring_outputs = offsprings[1][self.outputs.columns].to_numpy() self.replaced = [] for row in range(offspring_targets.shape[0]): y = offspring_targets[row] y_violation = 0.0 if offspring_violations is None else offspring_violations[row] # 2007 Step 2.3 / 2009 Step 2.4: update the ideal point. self.ideal_point = np.minimum(self.ideal_point, y) # 2009 Step 2.5: visit the pool in random order and stop after n_r replacements. With # no cap, the order does not matter and this is 2007 Step 2.4. order = self.rng.permutation(self._pool) g_new = self._aggregate(np.broadcast_to(y, (len(order), len(y))), order) g_old = self._aggregate(self._targets[order], order) old_violations = self._violations[order] better = (y_violation < old_violations) | ((y_violation == old_violations) & (g_new <= g_old)) winners = order[better] if self.max_replacements is not None: winners = winners[: self.max_replacements] self._variables[winners] = offspring_variables[row] self._outputs[winners] = offspring_outputs[row] self._targets[winners] = y self._violations[winners] = y_violation self.replaced.extend(winners.tolist()) if self.replaced: self.solutions = pl.DataFrame(self._variables, schema=self.solutions.schema, orient="row") self.outputs = pl.DataFrame(self._outputs, schema=self.outputs.schema, orient="row") return self.solutions, self.outputs ``` ##### mating_pool ``` mating_pool(subproblem: int) -> np.ndarray ``` Draw the mating pool of a subproblem, which is also the range the offspring may replace in. This is Step 2.1 of MOEA/D-DE. With `neighbourhood_probability = 1` it is always the neighbourhood, as in the original MOEA/D. The pool is remembered for the next call to `do`. Parameters: | Name | Type | Description | Default | | ------------ | ----- | ------------------------------------------------------------------- | ---------- | | `subproblem` | `int` | The index i of the subproblem an offspring is about to be made for. | *required* | Returns: | Type | Description | | --------- | ----------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: The indices of the subproblems in the pool. Always contains subproblem. | Source code in `desdeo/emo/operators/selection.py` ``` def mating_pool(self, subproblem: int) -> np.ndarray: """Draw the mating pool of a subproblem, which is also the range the offspring may replace in. This is Step 2.1 of MOEA/D-DE. With `neighbourhood_probability = 1` it is always the neighbourhood, as in the original MOEA/D. The pool is remembered for the next call to `do`. Args: subproblem (int): The index `i` of the subproblem an offspring is about to be made for. Returns: np.ndarray: The indices of the subproblems in the pool. Always contains `subproblem`. """ if self.rng.random() < self.neighbourhood_probability: pool = self.neighbourhoods[subproblem] else: pool = np.arange(self.number_of_subproblems) self._subproblem = subproblem self._pool = pool return pool ``` ##### state ``` state() -> Sequence[Message] ``` Return the operator's state as messages for the current verbosity level. Source code in `desdeo/emo/operators/selection.py` ``` def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.solutions is None: return [] state = DictMessage( topic=SelectorMessageTopics.STATE, value={ "population_size": self.number_of_subproblems, "ideal_point": self.ideal_point.tolist(), }, source=self.__class__.__name__, ) if self.verbosity == 1: return [state] return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), state, PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.solutions.hstack(self.outputs), source=self.__class__.__name__, ), ] ``` ##### update ``` update(message: Message) -> None ``` Handle an incoming message. This operator does not react to messages. Source code in `desdeo/emo/operators/selection.py` ``` def update(self, message: Message) -> None: """Handle an incoming message. This operator does not react to messages.""" ``` #### ModifiedWASFGASelector Bases: `_FitnessPublishingSelector` The environmental selection of Modified WASF-GA, the evolutionary part of IRA-EMO. The parents and the offspring are sorted into fronts by an achievement scalarizing function (ASF) that uses two reference points: an aspiration point, the values the decision maker would like to reach, and a reservation point, the values they will not accept anything worse than. The weight vectors alternate between the two, the even ones going with the reservation point and the odd ones with the aspiration point (`RankingASFs`). Front 1 takes, for each weight vector in turn, the solution not yet placed with the lowest ASF value for that vector and its reference point. Front 2 does the same with the solutions that remain, and so on. The next population is filled front by front, and the last front that fits only partly is cut in the order its members were placed. The final population thus approximates the parts of the Pareto front that project onto the two points; IRA-EMO keeps the solutions between them for the decision maker. Without levels the aspiration point is the ideal point and the reservation point the nadir point, both estimated from the run, which is the setting of Global WASF-GA. The ASF is normalised by an ideal and a nadir point estimated from every solution the selector has seen in the run, as the reference code does when `estimatePoints` is on. The reference code normalises only the aspiration ASF this way and leaves the reservation ASF with its initial bounds (`Double.MAX_VALUE` and `Double.MIN_VALUE`), which flips the sign of the reservation half; here both use the estimated bounds. Other departures from the reference code: the weight vectors for three or more objectives (see `modified_wasfga_weights`), and constraint handling, which the reference code lacks. As WASF-GA's paper describes, feasible solutions are sorted into fronts by the ASF and infeasible ones follow, one per front, in order of increasing total constraint violation. The published fitness is `1 / (1 + front)`, with the first front at zero, so it is positive and higher is better. References Saborido, R., Ruiz, A. B., Luque, M., & Miettinen, K. (2019). IRA-EMO: Interactive method using reservation and aspiration levels for evolutionary multiobjective optimization. In K. Deb et al. (Eds.), Evolutionary Multi-Criterion Optimization (EMO 2019), LNCS 11411, pp. 618-630. Springer. https://doi.org/10.1007/978-3-030-12598-1_49 Ruiz, A. B., Saborido, R., & Luque, M. (2015). A preference-based evolutionary algorithm for multiobjective optimization: The weighting achievement scalarizing function genetic algorithm. Journal of Global Optimization, 62(1), 101-129. https://doi.org/10.1007/s10898-014-0214-y Source code in `desdeo/emo/operators/selection.py` ``` class ModifiedWASFGASelector(_FitnessPublishingSelector): """The environmental selection of Modified WASF-GA, the evolutionary part of IRA-EMO. The parents and the offspring are sorted into fronts by an achievement scalarizing function (ASF) that uses two reference points: an aspiration point, the values the decision maker would like to reach, and a reservation point, the values they will not accept anything worse than. The weight vectors alternate between the two, the even ones going with the reservation point and the odd ones with the aspiration point (`RankingASFs`). Front 1 takes, for each weight vector in turn, the solution not yet placed with the lowest ASF value for that vector and its reference point. Front 2 does the same with the solutions that remain, and so on. The next population is filled front by front, and the last front that fits only partly is cut in the order its members were placed. The final population thus approximates the parts of the Pareto front that project onto the two points; IRA-EMO keeps the solutions between them for the decision maker. Without levels the aspiration point is the ideal point and the reservation point the nadir point, both estimated from the run, which is the setting of Global WASF-GA. The ASF is normalised by an ideal and a nadir point estimated from every solution the selector has seen in the run, as the reference code does when `estimatePoints` is on. The reference code normalises only the aspiration ASF this way and leaves the reservation ASF with its initial bounds (`Double.MAX_VALUE` and `Double.MIN_VALUE`), which flips the sign of the reservation half; here both use the estimated bounds. Other departures from the reference code: the weight vectors for three or more objectives (see `modified_wasfga_weights`), and constraint handling, which the reference code lacks. As WASF-GA's paper describes, feasible solutions are sorted into fronts by the ASF and infeasible ones follow, one per front, in order of increasing total constraint violation. The published fitness is `1 / (1 + front)`, with the first front at zero, so it is positive and higher is better. References: Saborido, R., Ruiz, A. B., Luque, M., & Miettinen, K. (2019). IRA-EMO: Interactive method using reservation and aspiration levels for evolutionary multiobjective optimization. In K. Deb et al. (Eds.), Evolutionary Multi-Criterion Optimization (EMO 2019), LNCS 11411, pp. 618-630. Springer. https://doi.org/10.1007/978-3-030-12598-1_49 Ruiz, A. B., Saborido, R., & Luque, M. (2015). A preference-based evolutionary algorithm for multiobjective optimization: The weighting achievement scalarizing function genetic algorithm. Journal of Global Optimization, 62(1), 101-129. https://doi.org/10.1007/s10898-014-0214-y """ def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, population_size: int, number_of_weights: int | None = None, aspiration_levels: dict[str, float] | None = None, reservation_levels: dict[str, float] | None = None, rho: float = 0.001, epsilon: float | None = None, seed: int = 0, ): """Initialize the selector. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. population_size (int): The number of solutions selected each generation. number_of_weights (int | None, optional): The number of weight vectors N_mu, split evenly between the two reference points. None uses `population_size`. Defaults to None. aspiration_levels (dict[str, float] | None, optional): The aspiration level of every objective, keyed by symbol and in the objective's own sense. None uses the estimated ideal point. Defaults to None. reservation_levels (dict[str, float] | None, optional): The reservation level of every objective, keyed by symbol and in the objective's own sense. None uses the estimated nadir point. Defaults to None. rho (float, optional): The augmentation coefficient of the ASF. Defaults to 0.001, the reference code's value. epsilon (float | None, optional): The smallest component of the vectors whose inverses are the weights. None uses the reference code's values, 0.01 for two objectives and 0.005 for more. Defaults to None. seed (int, optional): The random seed to use. The selection itself draws nothing. Defaults to 0. Raises: ValueError: If levels are given for a problem whose targets are not its objectives, or if they miss an objective. """ super().__init__( problem=problem, verbosity=verbosity, publisher=publisher, population_size=population_size, seed=seed ) n_objectives = len(self.target_symbols) self.number_of_weights = population_size if number_of_weights is None else number_of_weights self.rho = rho self.epsilon = epsilon if epsilon is not None else (0.01 if n_objectives == 2 else 0.005) # noqa: PLR2004 self.weights = modified_wasfga_weights(n_objectives, self.number_of_weights, self.epsilon) # Even weight vectors go with the reservation point, odd ones with the aspiration point. self.uses_aspiration = np.arange(self.number_of_weights) % 2 == 1 self.aspiration = self._minimised(aspiration_levels) self.reservation = self._minimised(reservation_levels) self.estimated_ideal: np.ndarray | None = None self.estimated_nadir: np.ndarray | None = None def _minimised(self, levels: dict[str, float] | None) -> np.ndarray | None: if levels is None: return None if self.problem.scalarization_funcs is not None: raise ValueError("Aspiration and reservation levels need a problem whose targets are its objectives.") missing = set(self.objective_symbols) - set(levels) if missing: raise ValueError(f"The levels miss the objectives {sorted(missing)}.") return np.array([levels[symbol] * self.maximization_mult[symbol] for symbol in self.objective_symbols]) def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Select the next population from the parents and the offspring. Args: parents (tuple[SolutionType, pl.DataFrame]): the population and its outputs. offsprings (tuple[SolutionType, pl.DataFrame]): the offspring and their outputs. Empty in the first generation. Returns: tuple[SolutionType, pl.DataFrame]: the next population and its outputs. """ solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy().astype(float) # IRAEMO.updateBounds: the bounds cover every solution evaluated in the run. lowest, highest = targets.min(axis=0), targets.max(axis=0) if self.estimated_ideal is None or self.estimated_nadir is None: self.estimated_ideal, self.estimated_nadir = lowest, highest else: self.estimated_ideal = np.minimum(self.estimated_ideal, lowest) self.estimated_nadir = np.maximum(self.estimated_nadir, highest) # TODO: not great aspiration = self.estimated_ideal if self.aspiration is None else self.aspiration reservation = self.estimated_nadir if self.reservation is None else self.reservation reference_points = np.where(self.uses_aspiration[:, None], aspiration, reservation) asf = modified_wasfga_asf( targets, reference_points, self.weights, self.estimated_ideal, self.estimated_nadir, self.rho ) violations = total_constraint_violation(outputs, self.constraints_symbols) feasible = np.ones(len(targets), dtype=bool) if violations is None else violations <= 0 chosen: list[int] = [] fronts: list[int] = [] placed = ~feasible front = 0 # RankingASFs: each front takes the best unplaced solution for every weight vector in turn. while len(chosen) < self.population_size and not placed.all(): for column in range(self.number_of_weights): if placed.all() or len(chosen) == self.population_size: break best = int(np.argmin(np.where(placed, np.inf, asf[:, column]))) placed[best] = True chosen.append(best) fronts.append(front) front += 1 # WASF-GA section 3: infeasible solutions follow, one per front, by increasing violation. if violations is not None and len(chosen) < self.population_size: infeasible = np.flatnonzero(~feasible) for best in infeasible[np.argsort(violations[infeasible], kind="stable")]: if len(chosen) == self.population_size: break chosen.append(int(best)) fronts.append(front) front += 1 return self._finish(solutions, outputs, chosen, 1.0 / (1.0 + np.array(fronts, dtype=float))) ``` ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, population_size: int, number_of_weights: int | None = None, aspiration_levels: dict[str, float] | None = None, reservation_levels: dict[str, float] | None = None, rho: float = 0.001, epsilon: float | None = None, seed: int = 0, ) ``` Initialize the selector. Parameters: | Name | Type | Description | Default | | -------------------- | ------------------ | --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | The optimization problem to be solved. | *required* | | `verbosity` | `int` | The verbosity level of the operator. | *required* | | `publisher` | `Publisher` | The publisher to use for communication. | *required* | | `population_size` | `int` | The number of solutions selected each generation. | *required* | | `number_of_weights` | \`int | None\` | The number of weight vectors N_mu, split evenly between the two reference points. None uses population_size. Defaults to None. | | `aspiration_levels` | \`dict[str, float] | None\` | The aspiration level of every objective, keyed by symbol and in the objective's own sense. None uses the estimated ideal point. Defaults to None. | | `reservation_levels` | \`dict[str, float] | None\` | The reservation level of every objective, keyed by symbol and in the objective's own sense. None uses the estimated nadir point. Defaults to None. | | `rho` | `float` | The augmentation coefficient of the ASF. Defaults to 0.001, the reference code's value. | `0.001` | | `epsilon` | \`float | None\` | The smallest component of the vectors whose inverses are the weights. None uses the reference code's values, 0.01 for two objectives and 0.005 for more. Defaults to None. | | `seed` | `int` | The random seed to use. The selection itself draws nothing. Defaults to 0. | `0` | Raises: | Type | Description | | ------------ | ----------------------------------------------------------------------------------------------------- | | `ValueError` | If levels are given for a problem whose targets are not its objectives, or if they miss an objective. | Source code in `desdeo/emo/operators/selection.py` ``` def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, population_size: int, number_of_weights: int | None = None, aspiration_levels: dict[str, float] | None = None, reservation_levels: dict[str, float] | None = None, rho: float = 0.001, epsilon: float | None = None, seed: int = 0, ): """Initialize the selector. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. population_size (int): The number of solutions selected each generation. number_of_weights (int | None, optional): The number of weight vectors N_mu, split evenly between the two reference points. None uses `population_size`. Defaults to None. aspiration_levels (dict[str, float] | None, optional): The aspiration level of every objective, keyed by symbol and in the objective's own sense. None uses the estimated ideal point. Defaults to None. reservation_levels (dict[str, float] | None, optional): The reservation level of every objective, keyed by symbol and in the objective's own sense. None uses the estimated nadir point. Defaults to None. rho (float, optional): The augmentation coefficient of the ASF. Defaults to 0.001, the reference code's value. epsilon (float | None, optional): The smallest component of the vectors whose inverses are the weights. None uses the reference code's values, 0.01 for two objectives and 0.005 for more. Defaults to None. seed (int, optional): The random seed to use. The selection itself draws nothing. Defaults to 0. Raises: ValueError: If levels are given for a problem whose targets are not its objectives, or if they miss an objective. """ super().__init__( problem=problem, verbosity=verbosity, publisher=publisher, population_size=population_size, seed=seed ) n_objectives = len(self.target_symbols) self.number_of_weights = population_size if number_of_weights is None else number_of_weights self.rho = rho self.epsilon = epsilon if epsilon is not None else (0.01 if n_objectives == 2 else 0.005) # noqa: PLR2004 self.weights = modified_wasfga_weights(n_objectives, self.number_of_weights, self.epsilon) # Even weight vectors go with the reservation point, odd ones with the aspiration point. self.uses_aspiration = np.arange(self.number_of_weights) % 2 == 1 self.aspiration = self._minimised(aspiration_levels) self.reservation = self._minimised(reservation_levels) self.estimated_ideal: np.ndarray | None = None self.estimated_nadir: np.ndarray | None = None ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Select the next population from the parents and the offspring. Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | --------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | the population and its outputs. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | the offspring and their outputs. Empty in the first generation. | *required* | Returns: | Type | Description | | -------------------------------- | ------------------------------------------------------------------------- | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: the next population and its outputs. | Source code in `desdeo/emo/operators/selection.py` ``` def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Select the next population from the parents and the offspring. Args: parents (tuple[SolutionType, pl.DataFrame]): the population and its outputs. offsprings (tuple[SolutionType, pl.DataFrame]): the offspring and their outputs. Empty in the first generation. Returns: tuple[SolutionType, pl.DataFrame]: the next population and its outputs. """ solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy().astype(float) # IRAEMO.updateBounds: the bounds cover every solution evaluated in the run. lowest, highest = targets.min(axis=0), targets.max(axis=0) if self.estimated_ideal is None or self.estimated_nadir is None: self.estimated_ideal, self.estimated_nadir = lowest, highest else: self.estimated_ideal = np.minimum(self.estimated_ideal, lowest) self.estimated_nadir = np.maximum(self.estimated_nadir, highest) # TODO: not great aspiration = self.estimated_ideal if self.aspiration is None else self.aspiration reservation = self.estimated_nadir if self.reservation is None else self.reservation reference_points = np.where(self.uses_aspiration[:, None], aspiration, reservation) asf = modified_wasfga_asf( targets, reference_points, self.weights, self.estimated_ideal, self.estimated_nadir, self.rho ) violations = total_constraint_violation(outputs, self.constraints_symbols) feasible = np.ones(len(targets), dtype=bool) if violations is None else violations <= 0 chosen: list[int] = [] fronts: list[int] = [] placed = ~feasible front = 0 # RankingASFs: each front takes the best unplaced solution for every weight vector in turn. while len(chosen) < self.population_size and not placed.all(): for column in range(self.number_of_weights): if placed.all() or len(chosen) == self.population_size: break best = int(np.argmin(np.where(placed, np.inf, asf[:, column]))) placed[best] = True chosen.append(best) fronts.append(front) front += 1 # WASF-GA section 3: infeasible solutions follow, one per front, by increasing violation. if violations is not None and len(chosen) < self.population_size: infeasible = np.flatnonzero(~feasible) for best in infeasible[np.argsort(violations[infeasible], kind="stable")]: if len(chosen) == self.population_size: break chosen.append(int(best)) fronts.append(front) front += 1 return self._finish(solutions, outputs, chosen, 1.0 / (1.0 + np.array(fronts, dtype=float))) ``` #### NSGA2Selector Bases: `_FitnessPublishingSelector` Implements the selection operator defined for NSGA2. Implements the selection operator defined for NSGA2, which included the crowding distance calculation. On a constrained problem the ranking switches to the constrained domination of the same paper: a feasible solution beats an infeasible one, two infeasible solutions are compared by total constraint violation, and two feasible solutions are compared by ordinary Pareto dominance. Nothing else changes, since that is where NSGA-II confines its constraint handling. Deb, K., Pratap, A., Agarwal, S., & Meyarivan, T. A. M. T. (2002). A fast and elitist multiobjective genetic algorithm: NSGA-II. IEEE transactions on evolutionary computation, 6(2), 182-197. Source code in `desdeo/emo/operators/selection.py` ``` class NSGA2Selector(_FitnessPublishingSelector): """Implements the selection operator defined for NSGA2. Implements the selection operator defined for NSGA2, which included the crowding distance calculation. On a constrained problem the ranking switches to the constrained domination of the same paper: a feasible solution beats an infeasible one, two infeasible solutions are compared by total constraint violation, and two feasible solutions are compared by ordinary Pareto dominance. Nothing else changes, since that is where NSGA-II confines its constraint handling. Reference: Deb, K., Pratap, A., Agarwal, S., & Meyarivan, T. A. M. T. (2002). A fast and elitist multiobjective genetic algorithm: NSGA-II. IEEE transactions on evolutionary computation, 6(2), 182-197. """ def _sort(self, targets: np.ndarray, violations: np.ndarray | None) -> np.ndarray: """Rank a population into fronts, applying constrained domination when the problem has constraints. Everything downstream -- crowding distance, the partial-front trim, the fitness -- is left alone, exactly as in NSGA-II, where constraint handling enters only through the ranking. See `constrained_fronts`. """ return constrained_fronts(targets, violations) def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation.""" # First iteration, offspring is empty # Do basic binary tournament selection, recombination, and mutation # In practice, just compute the non-dom ranks and provide them as fitness # Off-spring empty (first iteration, compute only non-dominated ranks and provide them as fitness) if offsprings[0].is_empty() and offsprings[1].is_empty(): # just compute non-dominated ranks of population and be done parents_a = parents[1][self.target_symbols].to_numpy() fronts = self._sort(parents_a, total_constraint_violation(parents[1], self.constraints_symbols)) # assign fitness according to non-dom rank, flipped to higher-is-better and kept # strictly positive for the consumers of SELECTED_FITNESS; see the main branch below scores = np.arange(len(fronts)) self.fitness = len(fronts) - scores @ fronts # all selected in first iteration self.selection = list(range(len(parents[1]))) self.selected_individuals = parents[0] self.selected_targets = parents[1] self.notify() return self.selected_individuals, self.selected_targets # #Actual selection operator for NSGA2 # Combine parent and offspring R_t = P_t U Q_t r_solutions = parents[0].vstack(offsprings[0]) r_population = parents[1].vstack(offsprings[1]) r_targets_arr = r_population[self.target_symbols].to_numpy() # the minimum and maximum target values in the whole current population f_mins, f_maxs = np.min(r_targets_arr, axis=0), np.max(r_targets_arr, axis=0) # Do fast non-dominated sorting on R_t -> F fronts = self._sort(r_targets_arr, total_constraint_violation(r_population, self.constraints_symbols)) crowding_distances = np.ones(self.population_size) * np.nan rankings = np.ones(self.population_size) * np.nan fitness_values = np.ones(self.population_size) * np.nan # Set the new parent population to P_t+1 = empty and i=1 new_parents = np.ones((self.population_size, parents[1].shape[1])) * np.nan new_parents_solutions = np.ones((self.population_size, parents[0].shape[1])) * np.nan parents_ptr = 0 # keep track where stuff was last added # the -1 is here because searchsorted returns the index where we can insert the population size to preserve the # order, hence, the previous index of this will be the last element in the cumsum that is less than # the population size last_whole_front_idx = ( np.searchsorted(np.cumsum(np.sum(fronts, axis=1)), self.population_size, side="right") - 1 ) last_ranking = 0 # in case first front is larger th population size for i in range(last_whole_front_idx + 1): # inclusive # The looped front here will result in a new population with size <= 100. # Compute the crowding distances for F_i distances = _nsga2_crowding_distance_assignment(r_targets_arr[fronts[i]], f_mins, f_maxs) crowding_distances[parents_ptr : parents_ptr + distances.shape[0]] = ( distances # distances will have same number of elements as in front[i] ) # keep track of the rankings as well (best = 0, larger worse). First # non-dom front will have a rank fitness of 0. rankings[parents_ptr : parents_ptr + distances.shape[0]] = i # P_t+1 = P_t+1 U F_i new_parents[parents_ptr : parents_ptr + distances.shape[0]] = r_population.filter(fronts[i]) new_parents_solutions[parents_ptr : parents_ptr + distances.shape[0]] = r_solutions.filter(fronts[i]) # compute fitness # infs are checked since boundary points are assigned this value when computing the crowding distance finite_distances = distances[distances != np.inf] max_no_inf = np.nanmax(finite_distances) if finite_distances.size > 0 else np.ones(fronts[i].sum()) distances_no_inf = np.nan_to_num(distances, posinf=max_no_inf * 1.1) # Distances for the current front normalized between 0 and 1. # The small scalar we add in the nominator and denominator is to # ensure that no distance value would result in exactly 0 after # normalizing, which would increase the corresponding solution # ranking, once reversed, which we do not want to. normalized_distances = (distances_no_inf - (distances_no_inf.min() - 1e-6)) / ( distances_no_inf.max() - (distances_no_inf.min() - 1e-6) ) # since higher is better for the crowded distance, we substract the normalized distances from 1 so that # lower is better, which allows us to combine them with the ranking # No value here should be 1.0 or greater. reversed_distances = 1.0 - normalized_distances front_fitness = reversed_distances + rankings[parents_ptr : parents_ptr + distances.shape[0]] fitness_values[parents_ptr : parents_ptr + distances.shape[0]] = front_fitness # increment parent pointer parents_ptr += distances.shape[0] # keep track of last given rank last_ranking = i # deal with last (partial) front, if needed trimmed_and_sorted_indices = None if parents_ptr < self.population_size: distances = _nsga2_crowding_distance_assignment( r_targets_arr[fronts[last_whole_front_idx + 1]], f_mins, f_maxs ) # Sort F_i in descending order according to crowding distance # This makes picking the selected part of the partial front easier trimmed_and_sorted_indices = distances.argsort()[::-1][: self.population_size - parents_ptr] crowding_distances[parents_ptr : self.population_size] = distances[trimmed_and_sorted_indices] rankings[parents_ptr : self.population_size] = last_ranking + 1 # P_t+1 = P_t+1 U F_i[1: (N - |P_t+1|)] new_parents[parents_ptr : self.population_size] = r_population.filter(fronts[last_whole_front_idx + 1])[ trimmed_and_sorted_indices ] new_parents_solutions[parents_ptr : self.population_size] = r_solutions.filter( fronts[last_whole_front_idx + 1] )[trimmed_and_sorted_indices] # compute fitness (see above for details) finite_distances = distances[trimmed_and_sorted_indices][distances[trimmed_and_sorted_indices] != np.inf] max_no_inf = ( np.nanmax(finite_distances) if finite_distances.size > 0 else np.ones(len(trimmed_and_sorted_indices)) # we have only boundary points ) distances_no_inf = np.nan_to_num(distances[trimmed_and_sorted_indices], posinf=max_no_inf * 1.1) normalized_distances = (distances_no_inf - (distances_no_inf.min() - 1e-6)) / ( distances_no_inf.max() - (distances_no_inf.min() - 1e-6) ) reversed_distances = 1.0 - normalized_distances front_fitness = reversed_distances + rankings[parents_ptr : self.population_size] fitness_values[parents_ptr : parents_ptr + self.population_size] = front_fitness # back to polars, return values solutions = pl.DataFrame(new_parents_solutions, schema=parents[0].schema) outputs = pl.DataFrame(new_parents, schema=parents[1].schema) # Everything downstream of SELECTED_FITNESS reads it as higher-is-better: the mating # tournament takes an argmax, and roulette-wheel selection treats it as a weight, which also # requires it to be positive. The NSGA-II quantity built above is the opposite -- front rank # plus a reversed crowding distance, lower is better -- so publishing it directly made the # binary tournament pick the loser of every pair. Reflecting it about the worst attainable # value flips the direction, keeps every value strictly positive (a front's fitness lies in # `(n_fronts - rank - 1, n_fronts - rank]`, since the reversed distance never reaches 1) and # preserves the ordering exactly. self.fitness = (np.nanmax(rankings) + 1.0) - fitness_values whole_fronts = fronts[: last_whole_front_idx + 1] whole_indices = [np.where(row)[0].tolist() for row in whole_fronts] if trimmed_and_sorted_indices is not None: # partial front considered partial_front = fronts[last_whole_front_idx + 1] partial_indices = np.where(partial_front)[0][trimmed_and_sorted_indices].tolist() else: partial_indices = [] self.selection = [index for indices in whole_indices for index in indices] + partial_indices self.selected_individuals = solutions self.selected_targets = outputs self.notify() return solutions, outputs ``` ##### \_sort ``` _sort( targets: ndarray, violations: ndarray | None ) -> np.ndarray ``` Rank a population into fronts, applying constrained domination when the problem has constraints. Everything downstream -- crowding distance, the partial-front trim, the fitness -- is left alone, exactly as in NSGA-II, where constraint handling enters only through the ranking. See `constrained_fronts`. Source code in `desdeo/emo/operators/selection.py` ``` def _sort(self, targets: np.ndarray, violations: np.ndarray | None) -> np.ndarray: """Rank a population into fronts, applying constrained domination when the problem has constraints. Everything downstream -- crowding distance, the partial-front trim, the fitness -- is left alone, exactly as in NSGA-II, where constraint handling enters only through the ranking. See `constrained_fronts`. """ return constrained_fronts(targets, violations) ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the selection operation. Source code in `desdeo/emo/operators/selection.py` ``` def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation.""" # First iteration, offspring is empty # Do basic binary tournament selection, recombination, and mutation # In practice, just compute the non-dom ranks and provide them as fitness # Off-spring empty (first iteration, compute only non-dominated ranks and provide them as fitness) if offsprings[0].is_empty() and offsprings[1].is_empty(): # just compute non-dominated ranks of population and be done parents_a = parents[1][self.target_symbols].to_numpy() fronts = self._sort(parents_a, total_constraint_violation(parents[1], self.constraints_symbols)) # assign fitness according to non-dom rank, flipped to higher-is-better and kept # strictly positive for the consumers of SELECTED_FITNESS; see the main branch below scores = np.arange(len(fronts)) self.fitness = len(fronts) - scores @ fronts # all selected in first iteration self.selection = list(range(len(parents[1]))) self.selected_individuals = parents[0] self.selected_targets = parents[1] self.notify() return self.selected_individuals, self.selected_targets # #Actual selection operator for NSGA2 # Combine parent and offspring R_t = P_t U Q_t r_solutions = parents[0].vstack(offsprings[0]) r_population = parents[1].vstack(offsprings[1]) r_targets_arr = r_population[self.target_symbols].to_numpy() # the minimum and maximum target values in the whole current population f_mins, f_maxs = np.min(r_targets_arr, axis=0), np.max(r_targets_arr, axis=0) # Do fast non-dominated sorting on R_t -> F fronts = self._sort(r_targets_arr, total_constraint_violation(r_population, self.constraints_symbols)) crowding_distances = np.ones(self.population_size) * np.nan rankings = np.ones(self.population_size) * np.nan fitness_values = np.ones(self.population_size) * np.nan # Set the new parent population to P_t+1 = empty and i=1 new_parents = np.ones((self.population_size, parents[1].shape[1])) * np.nan new_parents_solutions = np.ones((self.population_size, parents[0].shape[1])) * np.nan parents_ptr = 0 # keep track where stuff was last added # the -1 is here because searchsorted returns the index where we can insert the population size to preserve the # order, hence, the previous index of this will be the last element in the cumsum that is less than # the population size last_whole_front_idx = ( np.searchsorted(np.cumsum(np.sum(fronts, axis=1)), self.population_size, side="right") - 1 ) last_ranking = 0 # in case first front is larger th population size for i in range(last_whole_front_idx + 1): # inclusive # The looped front here will result in a new population with size <= 100. # Compute the crowding distances for F_i distances = _nsga2_crowding_distance_assignment(r_targets_arr[fronts[i]], f_mins, f_maxs) crowding_distances[parents_ptr : parents_ptr + distances.shape[0]] = ( distances # distances will have same number of elements as in front[i] ) # keep track of the rankings as well (best = 0, larger worse). First # non-dom front will have a rank fitness of 0. rankings[parents_ptr : parents_ptr + distances.shape[0]] = i # P_t+1 = P_t+1 U F_i new_parents[parents_ptr : parents_ptr + distances.shape[0]] = r_population.filter(fronts[i]) new_parents_solutions[parents_ptr : parents_ptr + distances.shape[0]] = r_solutions.filter(fronts[i]) # compute fitness # infs are checked since boundary points are assigned this value when computing the crowding distance finite_distances = distances[distances != np.inf] max_no_inf = np.nanmax(finite_distances) if finite_distances.size > 0 else np.ones(fronts[i].sum()) distances_no_inf = np.nan_to_num(distances, posinf=max_no_inf * 1.1) # Distances for the current front normalized between 0 and 1. # The small scalar we add in the nominator and denominator is to # ensure that no distance value would result in exactly 0 after # normalizing, which would increase the corresponding solution # ranking, once reversed, which we do not want to. normalized_distances = (distances_no_inf - (distances_no_inf.min() - 1e-6)) / ( distances_no_inf.max() - (distances_no_inf.min() - 1e-6) ) # since higher is better for the crowded distance, we substract the normalized distances from 1 so that # lower is better, which allows us to combine them with the ranking # No value here should be 1.0 or greater. reversed_distances = 1.0 - normalized_distances front_fitness = reversed_distances + rankings[parents_ptr : parents_ptr + distances.shape[0]] fitness_values[parents_ptr : parents_ptr + distances.shape[0]] = front_fitness # increment parent pointer parents_ptr += distances.shape[0] # keep track of last given rank last_ranking = i # deal with last (partial) front, if needed trimmed_and_sorted_indices = None if parents_ptr < self.population_size: distances = _nsga2_crowding_distance_assignment( r_targets_arr[fronts[last_whole_front_idx + 1]], f_mins, f_maxs ) # Sort F_i in descending order according to crowding distance # This makes picking the selected part of the partial front easier trimmed_and_sorted_indices = distances.argsort()[::-1][: self.population_size - parents_ptr] crowding_distances[parents_ptr : self.population_size] = distances[trimmed_and_sorted_indices] rankings[parents_ptr : self.population_size] = last_ranking + 1 # P_t+1 = P_t+1 U F_i[1: (N - |P_t+1|)] new_parents[parents_ptr : self.population_size] = r_population.filter(fronts[last_whole_front_idx + 1])[ trimmed_and_sorted_indices ] new_parents_solutions[parents_ptr : self.population_size] = r_solutions.filter( fronts[last_whole_front_idx + 1] )[trimmed_and_sorted_indices] # compute fitness (see above for details) finite_distances = distances[trimmed_and_sorted_indices][distances[trimmed_and_sorted_indices] != np.inf] max_no_inf = ( np.nanmax(finite_distances) if finite_distances.size > 0 else np.ones(len(trimmed_and_sorted_indices)) # we have only boundary points ) distances_no_inf = np.nan_to_num(distances[trimmed_and_sorted_indices], posinf=max_no_inf * 1.1) normalized_distances = (distances_no_inf - (distances_no_inf.min() - 1e-6)) / ( distances_no_inf.max() - (distances_no_inf.min() - 1e-6) ) reversed_distances = 1.0 - normalized_distances front_fitness = reversed_distances + rankings[parents_ptr : self.population_size] fitness_values[parents_ptr : parents_ptr + self.population_size] = front_fitness # back to polars, return values solutions = pl.DataFrame(new_parents_solutions, schema=parents[0].schema) outputs = pl.DataFrame(new_parents, schema=parents[1].schema) # Everything downstream of SELECTED_FITNESS reads it as higher-is-better: the mating # tournament takes an argmax, and roulette-wheel selection treats it as a weight, which also # requires it to be positive. The NSGA-II quantity built above is the opposite -- front rank # plus a reversed crowding distance, lower is better -- so publishing it directly made the # binary tournament pick the loser of every pair. Reflecting it about the worst attainable # value flips the direction, keeps every value strictly positive (a front's fitness lies in # `(n_fronts - rank - 1, n_fronts - rank]`, since the reversed distance never reaches 1) and # preserves the ordering exactly. self.fitness = (np.nanmax(rankings) + 1.0) - fitness_values whole_fronts = fronts[: last_whole_front_idx + 1] whole_indices = [np.where(row)[0].tolist() for row in whole_fronts] if trimmed_and_sorted_indices is not None: # partial front considered partial_front = fronts[last_whole_front_idx + 1] partial_indices = np.where(partial_front)[0][trimmed_and_sorted_indices].tolist() else: partial_indices = [] self.selection = [index for indices in whole_indices for index in indices] + partial_indices self.selected_individuals = solutions self.selected_targets = outputs self.notify() return solutions, outputs ``` #### NSGA3Selector Bases: `BaseDecompositionSelector` The NSGA-III selection operator, heavily based on the version of nsga3 in the pymoo package by msu-coinlab. Source code in `desdeo/emo/operators/selection.py` ``` class NSGA3Selector(BaseDecompositionSelector): """The NSGA-III selection operator, heavily based on the version of nsga3 in the pymoo package by msu-coinlab.""" @property def provided_topics(self): """The message topics this operator publishes, keyed by verbosity level.""" return { 0: [], 1: [ SelectorMessageTopics.STATE, ], 2: [ SelectorMessageTopics.REFERENCE_VECTORS, SelectorMessageTopics.STATE, SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, ], } @property def interested_topics(self): """The message topics this operator subscribes to.""" return [] def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, reference_vector_options: ReferenceVectorOptions | None = None, invert_reference_vectors: bool = False, seed: int = 0, ): """Initialize the NSGA-III selection operator. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. reference_vector_options (ReferenceVectorOptions | None, optional): Reference vector options. Defaults to None. invert_reference_vectors (bool, optional): Whether to invert the reference vectors. Defaults to False. seed (int, optional): The random seed to use. Defaults to 0. """ if reference_vector_options is None: reference_vector_options = ReferenceVectorOptions() elif isinstance(reference_vector_options, dict): reference_vector_options = ReferenceVectorOptions.model_validate(reference_vector_options) # Just asserting correct options for NSGA-III reference_vector_options.vector_type = "planar" super().__init__( problem, reference_vector_options=reference_vector_options, verbosity=verbosity, publisher=publisher, seed=seed, invert_reference_vectors=invert_reference_vectors, ) self.adapted_reference_vectors = None self.worst_fitness: np.ndarray | None = None self.extreme_points: np.ndarray | None = None self.n_survive = self.reference_vectors.shape[0] self.selection: list[int] | None = None self.selected_individuals: SolutionType | None = None self.selected_targets: pl.DataFrame | None = None def do( # NOQA: C901 self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ if isinstance(parents[0], pl.DataFrame) and isinstance(offsprings[0], pl.DataFrame): solutions = parents[0].vstack(offsprings[0]) elif isinstance(parents[0], list) and isinstance(offsprings[0], list): solutions = parents[0] + offsprings[0] else: raise TypeError("The decision variables must be either a list or a polars DataFrame, not both") alltargets = parents[1].vstack(offsprings[1]) # Check if there are constraints and filter feasible solutions if self.constraints_symbols is not None and len(self.constraints_symbols) > 0: constraints = alltargets[self.constraints_symbols].to_numpy() constraints = np.where(constraints > 0, constraints, 0) constraints_sum = np.sum(constraints, axis=1) feasible = np.where(constraints_sum == 0)[0].tolist() sorted_infeasible = constraints_sum.argsort().tolist()[len(feasible) :] if len(feasible) <= self.n_survive: # Put all feasible solutions in the selection, then fill the rest with the least constraint violation select = feasible.copy() remaining = self.n_survive - len(select) select += sorted_infeasible[:remaining] self.selection = select if isinstance(solutions, pl.DataFrame) and self.selection is not None: self.selected_individuals = solutions[self.selection] elif isinstance(solutions, list) and self.selection is not None: self.selected_individuals = [solutions[i] for i in self.selection] else: raise RuntimeError("Something went wrong with the selection") self.selected_targets = alltargets[self.selection] self.notify() return self.selected_individuals, self.selected_targets # else: # Only consider feasible solutions for selection if isinstance(solutions, pl.DataFrame): solutions = solutions[feasible] elif isinstance(solutions, list): solutions = [solutions[i] for i in feasible] alltargets = alltargets[feasible] targets = alltargets[self.target_symbols].to_numpy() ref_dirs = self.reference_vectors if self.ideal is None: self.ideal = np.min(targets, axis=0) else: self.ideal = np.min(np.vstack((self.ideal, np.min(targets, axis=0))), axis=0) fitness = targets # Calculating fronts and ranks # fronts, dl, dc, rank = nds(fitness) fronts = fast_non_dominated_sort(fitness) fronts = [np.where(fronts[i])[0] for i in range(len(fronts))] non_dominated = fronts[0] if self.worst_fitness is None: self.worst_fitness = np.max(fitness, axis=0) else: self.worst_fitness = np.amax(np.vstack((self.worst_fitness, fitness)), axis=0) # Calculating worst points worst_of_population = np.amax(fitness, axis=0) worst_of_front = np.max(fitness[non_dominated, :], axis=0) self.extreme_points = self.get_extreme_points_c( fitness[non_dominated, :], self.ideal, extreme_points=self.extreme_points ) self.nadir_point = nadir_point = self.get_nadir_point( self.extreme_points, self.ideal, self.worst_fitness, worst_of_population, worst_of_front, ) # Finding individuals in first 'n' fronts selection = np.asarray([], dtype=int) for front_id in range(len(fronts)): if len(np.concatenate(fronts[: front_id + 1])) < self.n_survive: continue fronts = fronts[: front_id + 1] selection = np.concatenate(fronts) break else: # The combined population is smaller than the desired number of survivors # (this happens, e.g., when preferred solutions inflate the number of # reference vectors beyond the population size). Keep all available solutions. if fronts: selection = np.concatenate(fronts) front_fitness = fitness[selection] last_front = fronts[-1] # Selecting individuals from the last acceptable front. if len(selection) > self.n_survive: niche_of_individuals, dist_to_niche = self.associate_to_niches( front_fitness, ref_dirs, self.ideal, nadir_point ) # if there is only one front if len(fronts) == 1: n_remaining = self.n_survive until_last_front = np.array([], dtype=int) niche_count = np.zeros(len(ref_dirs), dtype=int) # if some individuals already survived else: until_last_front = np.concatenate(fronts[:-1]) id_until_last_front = list(range(len(until_last_front))) niche_count = self.calc_niche_count(len(ref_dirs), niche_of_individuals[id_until_last_front]) n_remaining = self.n_survive - len(until_last_front) last_front_selection_id = list(range(len(until_last_front), len(selection))) selected_from_last_front = self.niching( fitness[last_front, :], n_remaining, niche_count, niche_of_individuals[last_front_selection_id], dist_to_niche[last_front_selection_id], ) final_selection = np.concatenate((until_last_front, last_front[selected_from_last_front])) else: final_selection = selection self.selection = final_selection.tolist() if isinstance(solutions, pl.DataFrame) and self.selection is not None: self.selected_individuals = solutions[self.selection] elif isinstance(solutions, list) and self.selection is not None: self.selected_individuals = [solutions[i] for i in self.selection] else: raise RuntimeError("Something went wrong with the selection") self.selected_targets = alltargets[self.selection] self.notify() return self.selected_individuals, self.selected_targets def get_extreme_points_c(self, f, ideal_point, extreme_points=None): """Find the extreme points used for normalization (adapted from pymoo).""" # calculate the asf which is used for the extreme point decomposition asf = np.eye(f.shape[1]) asf[asf == 0] = 1e6 # add the old extreme points to never loose them for normalization all_f = f if extreme_points is not None: all_f = np.concatenate([extreme_points, all_f], axis=0) # translate so that small values are substituted to 0 near_zero_tolerance = 1e-3 translated_f = all_f - ideal_point translated_f[translated_f < near_zero_tolerance] = 0 # update the extreme points for the normalization having the highest asf value each f_asf = np.max(translated_f * asf[:, None, :], axis=2) min_idx = np.argmin(f_asf, axis=1) return all_f[min_idx, :] def get_nadir_point( self, extreme_points, ideal_point, worst_point, worst_of_front, worst_of_population, ): """Estimate the nadir point from the extreme points (adapted from pymoo).""" degenerate_tolerance = 1e-6 try: # find the intercepts using gaussian elimination coeff_matrix = extreme_points - ideal_point b = np.ones(extreme_points.shape[1]) plane = np.linalg.solve(coeff_matrix, b) intercepts = 1 / plane nadir_point = ideal_point + intercepts if ( not np.allclose(np.dot(coeff_matrix, plane), b) or np.any(intercepts <= degenerate_tolerance) or np.any(nadir_point > worst_point) ): raise np.linalg.LinAlgError # noqa: TRY301 except np.linalg.LinAlgError: nadir_point = worst_of_front b = nadir_point - ideal_point <= degenerate_tolerance nadir_point[b] = worst_of_population[b] return nadir_point def niching(self, f, n_remaining, niche_count, niche_of_individuals, dist_to_niche): """Select survivors from the last front by reference-vector niching (adapted from pymoo).""" survivors = [] # boolean array of elements that are considered for each iteration mask = np.full(f.shape[0], fill_value=True) while len(survivors) < n_remaining: # all niches where new individuals can be assigned to next_niches_list = np.unique(niche_of_individuals[mask]) # pick a niche with minimum assigned individuals - break tie if necessary next_niche_count = niche_count[next_niches_list] next_niche = np.where(next_niche_count == next_niche_count.min())[0] next_niche = next_niches_list[next_niche] next_niche = next_niche[self.rng.integers(0, len(next_niche))] # indices of individuals that are considered and assign to next_niche next_ind = np.where(np.logical_and(niche_of_individuals == next_niche, mask))[0] # shuffle to break random tie (equal perp. dist) or select randomly self.rng.shuffle(next_ind) # if the niche is empty, take the closest individual; otherwise take a random one (already shuffled) next_ind = next_ind[np.argmin(dist_to_niche[next_ind])] if niche_count[next_niche] == 0 else next_ind[0] mask[next_ind] = False survivors.append(int(next_ind)) niche_count[next_niche] += 1 return survivors def associate_to_niches(self, f, ref_dirs, ideal_point, nadir_point, utopian_epsilon=0.0): """Associate each solution with its closest reference vector (adapted from pymoo).""" utopian_point = ideal_point - utopian_epsilon denom = nadir_point - utopian_point denom[denom == 0] = 1e-12 # normalize by ideal point and intercepts normalized = (f - utopian_point) / denom dist_matrix = jitted_calc_perpendicular_distance(normalized, ref_dirs, self.invert_reference_vectors) niche_of_individuals = np.argmin(dist_matrix, axis=1) dist_to_niche = dist_matrix[np.arange(f.shape[0]), niche_of_individuals] return niche_of_individuals, dist_to_niche def calc_niche_count(self, n_niches, niche_of_individuals): """Count how many of the given individuals are assigned to each niche.""" niche_count = np.zeros(n_niches, dtype=int) index, count = np.unique(niche_of_individuals, return_counts=True) niche_count[index] = count return niche_count def calc_perpendicular_distance(self, normalized, ref_dirs): """Compute the perpendicular distance from each normalized solution to each reference direction.""" if self.invert_reference_vectors: u = np.tile(-ref_dirs, (len(normalized), 1)) v = np.repeat(1 - normalized, len(ref_dirs), axis=0) else: u = np.tile(ref_dirs, (len(normalized), 1)) v = np.repeat(normalized, len(ref_dirs), axis=0) norm_u = np.linalg.norm(u, axis=1) scalar_proj = np.sum(v * u, axis=1) / norm_u proj = scalar_proj[:, None] * u / norm_u[:, None] val = np.linalg.norm(proj - v, axis=1) return np.reshape(val, (len(normalized), len(ref_dirs))) def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.selection is None or self.selected_targets is None: return [] if self.verbosity == 1: return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), DictMessage( topic=SelectorMessageTopics.STATE, value={ "ideal": self.ideal, "nadir": self.worst_fitness, "extreme_points": self.extreme_points, "n_survive": self.n_survive, }, source=self.__class__.__name__, ), ] # verbosity == 2 if isinstance(self.selected_individuals, pl.DataFrame): message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_targets, source=self.__class__.__name__, ) return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), DictMessage( topic=SelectorMessageTopics.STATE, value={ "ideal": self.ideal, "nadir": self.worst_fitness, "extreme_points": self.extreme_points, "n_survive": self.n_survive, }, source=self.__class__.__name__, ), # Array2DMessage( # topic=SelectorMessageTopics.SELECTED_INDIVIDUALS, # value=self.selected_individuals, # source=self.__class__.__name__, # ), message, ] def update(self, message: Message) -> None: """Handle an incoming message. This operator does not react to messages.""" ``` ##### interested_topics ``` interested_topics ``` The message topics this operator subscribes to. ##### provided_topics ``` provided_topics ``` The message topics this operator publishes, keyed by verbosity level. ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, reference_vector_options: ReferenceVectorOptions | None = None, invert_reference_vectors: bool = False, seed: int = 0, ) ``` Initialize the NSGA-III selection operator. Parameters: | Name | Type | Description | Default | | -------------------------- | ------------------------ | ----------------------------------------------------------- | ------------------------------------------- | | `problem` | `Problem` | The optimization problem to be solved. | *required* | | `verbosity` | `int` | The verbosity level of the operator. | *required* | | `publisher` | `Publisher` | The publisher to use for communication. | *required* | | `reference_vector_options` | \`ReferenceVectorOptions | None\` | Reference vector options. Defaults to None. | | `invert_reference_vectors` | `bool` | Whether to invert the reference vectors. Defaults to False. | `False` | | `seed` | `int` | The random seed to use. Defaults to 0. | `0` | Source code in `desdeo/emo/operators/selection.py` ``` def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, reference_vector_options: ReferenceVectorOptions | None = None, invert_reference_vectors: bool = False, seed: int = 0, ): """Initialize the NSGA-III selection operator. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. reference_vector_options (ReferenceVectorOptions | None, optional): Reference vector options. Defaults to None. invert_reference_vectors (bool, optional): Whether to invert the reference vectors. Defaults to False. seed (int, optional): The random seed to use. Defaults to 0. """ if reference_vector_options is None: reference_vector_options = ReferenceVectorOptions() elif isinstance(reference_vector_options, dict): reference_vector_options = ReferenceVectorOptions.model_validate(reference_vector_options) # Just asserting correct options for NSGA-III reference_vector_options.vector_type = "planar" super().__init__( problem, reference_vector_options=reference_vector_options, verbosity=verbosity, publisher=publisher, seed=seed, invert_reference_vectors=invert_reference_vectors, ) self.adapted_reference_vectors = None self.worst_fitness: np.ndarray | None = None self.extreme_points: np.ndarray | None = None self.n_survive = self.reference_vectors.shape[0] self.selection: list[int] | None = None self.selected_individuals: SolutionType | None = None self.selected_targets: pl.DataFrame | None = None ``` ##### associate_to_niches ``` associate_to_niches( f, ref_dirs, ideal_point, nadir_point, utopian_epsilon=0.0, ) ``` Associate each solution with its closest reference vector (adapted from pymoo). Source code in `desdeo/emo/operators/selection.py` ``` def associate_to_niches(self, f, ref_dirs, ideal_point, nadir_point, utopian_epsilon=0.0): """Associate each solution with its closest reference vector (adapted from pymoo).""" utopian_point = ideal_point - utopian_epsilon denom = nadir_point - utopian_point denom[denom == 0] = 1e-12 # normalize by ideal point and intercepts normalized = (f - utopian_point) / denom dist_matrix = jitted_calc_perpendicular_distance(normalized, ref_dirs, self.invert_reference_vectors) niche_of_individuals = np.argmin(dist_matrix, axis=1) dist_to_niche = dist_matrix[np.arange(f.shape[0]), niche_of_individuals] return niche_of_individuals, dist_to_niche ``` ##### calc_niche_count ``` calc_niche_count(n_niches, niche_of_individuals) ``` Count how many of the given individuals are assigned to each niche. Source code in `desdeo/emo/operators/selection.py` ``` def calc_niche_count(self, n_niches, niche_of_individuals): """Count how many of the given individuals are assigned to each niche.""" niche_count = np.zeros(n_niches, dtype=int) index, count = np.unique(niche_of_individuals, return_counts=True) niche_count[index] = count return niche_count ``` ##### calc_perpendicular_distance ``` calc_perpendicular_distance(normalized, ref_dirs) ``` Compute the perpendicular distance from each normalized solution to each reference direction. Source code in `desdeo/emo/operators/selection.py` ``` def calc_perpendicular_distance(self, normalized, ref_dirs): """Compute the perpendicular distance from each normalized solution to each reference direction.""" if self.invert_reference_vectors: u = np.tile(-ref_dirs, (len(normalized), 1)) v = np.repeat(1 - normalized, len(ref_dirs), axis=0) else: u = np.tile(ref_dirs, (len(normalized), 1)) v = np.repeat(normalized, len(ref_dirs), axis=0) norm_u = np.linalg.norm(u, axis=1) scalar_proj = np.sum(v * u, axis=1) / norm_u proj = scalar_proj[:, None] * u / norm_u[:, None] val = np.linalg.norm(proj - v, axis=1) return np.reshape(val, (len(normalized), len(ref_dirs))) ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the selection operation. Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | Returns: | Type | Description | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: The selected decision variables and their objective values, targets, and constraint violations. | Source code in `desdeo/emo/operators/selection.py` ``` def do( # NOQA: C901 self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ if isinstance(parents[0], pl.DataFrame) and isinstance(offsprings[0], pl.DataFrame): solutions = parents[0].vstack(offsprings[0]) elif isinstance(parents[0], list) and isinstance(offsprings[0], list): solutions = parents[0] + offsprings[0] else: raise TypeError("The decision variables must be either a list or a polars DataFrame, not both") alltargets = parents[1].vstack(offsprings[1]) # Check if there are constraints and filter feasible solutions if self.constraints_symbols is not None and len(self.constraints_symbols) > 0: constraints = alltargets[self.constraints_symbols].to_numpy() constraints = np.where(constraints > 0, constraints, 0) constraints_sum = np.sum(constraints, axis=1) feasible = np.where(constraints_sum == 0)[0].tolist() sorted_infeasible = constraints_sum.argsort().tolist()[len(feasible) :] if len(feasible) <= self.n_survive: # Put all feasible solutions in the selection, then fill the rest with the least constraint violation select = feasible.copy() remaining = self.n_survive - len(select) select += sorted_infeasible[:remaining] self.selection = select if isinstance(solutions, pl.DataFrame) and self.selection is not None: self.selected_individuals = solutions[self.selection] elif isinstance(solutions, list) and self.selection is not None: self.selected_individuals = [solutions[i] for i in self.selection] else: raise RuntimeError("Something went wrong with the selection") self.selected_targets = alltargets[self.selection] self.notify() return self.selected_individuals, self.selected_targets # else: # Only consider feasible solutions for selection if isinstance(solutions, pl.DataFrame): solutions = solutions[feasible] elif isinstance(solutions, list): solutions = [solutions[i] for i in feasible] alltargets = alltargets[feasible] targets = alltargets[self.target_symbols].to_numpy() ref_dirs = self.reference_vectors if self.ideal is None: self.ideal = np.min(targets, axis=0) else: self.ideal = np.min(np.vstack((self.ideal, np.min(targets, axis=0))), axis=0) fitness = targets # Calculating fronts and ranks # fronts, dl, dc, rank = nds(fitness) fronts = fast_non_dominated_sort(fitness) fronts = [np.where(fronts[i])[0] for i in range(len(fronts))] non_dominated = fronts[0] if self.worst_fitness is None: self.worst_fitness = np.max(fitness, axis=0) else: self.worst_fitness = np.amax(np.vstack((self.worst_fitness, fitness)), axis=0) # Calculating worst points worst_of_population = np.amax(fitness, axis=0) worst_of_front = np.max(fitness[non_dominated, :], axis=0) self.extreme_points = self.get_extreme_points_c( fitness[non_dominated, :], self.ideal, extreme_points=self.extreme_points ) self.nadir_point = nadir_point = self.get_nadir_point( self.extreme_points, self.ideal, self.worst_fitness, worst_of_population, worst_of_front, ) # Finding individuals in first 'n' fronts selection = np.asarray([], dtype=int) for front_id in range(len(fronts)): if len(np.concatenate(fronts[: front_id + 1])) < self.n_survive: continue fronts = fronts[: front_id + 1] selection = np.concatenate(fronts) break else: # The combined population is smaller than the desired number of survivors # (this happens, e.g., when preferred solutions inflate the number of # reference vectors beyond the population size). Keep all available solutions. if fronts: selection = np.concatenate(fronts) front_fitness = fitness[selection] last_front = fronts[-1] # Selecting individuals from the last acceptable front. if len(selection) > self.n_survive: niche_of_individuals, dist_to_niche = self.associate_to_niches( front_fitness, ref_dirs, self.ideal, nadir_point ) # if there is only one front if len(fronts) == 1: n_remaining = self.n_survive until_last_front = np.array([], dtype=int) niche_count = np.zeros(len(ref_dirs), dtype=int) # if some individuals already survived else: until_last_front = np.concatenate(fronts[:-1]) id_until_last_front = list(range(len(until_last_front))) niche_count = self.calc_niche_count(len(ref_dirs), niche_of_individuals[id_until_last_front]) n_remaining = self.n_survive - len(until_last_front) last_front_selection_id = list(range(len(until_last_front), len(selection))) selected_from_last_front = self.niching( fitness[last_front, :], n_remaining, niche_count, niche_of_individuals[last_front_selection_id], dist_to_niche[last_front_selection_id], ) final_selection = np.concatenate((until_last_front, last_front[selected_from_last_front])) else: final_selection = selection self.selection = final_selection.tolist() if isinstance(solutions, pl.DataFrame) and self.selection is not None: self.selected_individuals = solutions[self.selection] elif isinstance(solutions, list) and self.selection is not None: self.selected_individuals = [solutions[i] for i in self.selection] else: raise RuntimeError("Something went wrong with the selection") self.selected_targets = alltargets[self.selection] self.notify() return self.selected_individuals, self.selected_targets ``` ##### get_extreme_points_c ``` get_extreme_points_c(f, ideal_point, extreme_points=None) ``` Find the extreme points used for normalization (adapted from pymoo). Source code in `desdeo/emo/operators/selection.py` ``` def get_extreme_points_c(self, f, ideal_point, extreme_points=None): """Find the extreme points used for normalization (adapted from pymoo).""" # calculate the asf which is used for the extreme point decomposition asf = np.eye(f.shape[1]) asf[asf == 0] = 1e6 # add the old extreme points to never loose them for normalization all_f = f if extreme_points is not None: all_f = np.concatenate([extreme_points, all_f], axis=0) # translate so that small values are substituted to 0 near_zero_tolerance = 1e-3 translated_f = all_f - ideal_point translated_f[translated_f < near_zero_tolerance] = 0 # update the extreme points for the normalization having the highest asf value each f_asf = np.max(translated_f * asf[:, None, :], axis=2) min_idx = np.argmin(f_asf, axis=1) return all_f[min_idx, :] ``` ##### get_nadir_point ``` get_nadir_point( extreme_points, ideal_point, worst_point, worst_of_front, worst_of_population, ) ``` Estimate the nadir point from the extreme points (adapted from pymoo). Source code in `desdeo/emo/operators/selection.py` ``` def get_nadir_point( self, extreme_points, ideal_point, worst_point, worst_of_front, worst_of_population, ): """Estimate the nadir point from the extreme points (adapted from pymoo).""" degenerate_tolerance = 1e-6 try: # find the intercepts using gaussian elimination coeff_matrix = extreme_points - ideal_point b = np.ones(extreme_points.shape[1]) plane = np.linalg.solve(coeff_matrix, b) intercepts = 1 / plane nadir_point = ideal_point + intercepts if ( not np.allclose(np.dot(coeff_matrix, plane), b) or np.any(intercepts <= degenerate_tolerance) or np.any(nadir_point > worst_point) ): raise np.linalg.LinAlgError # noqa: TRY301 except np.linalg.LinAlgError: nadir_point = worst_of_front b = nadir_point - ideal_point <= degenerate_tolerance nadir_point[b] = worst_of_population[b] return nadir_point ``` ##### niching ``` niching( f, n_remaining, niche_count, niche_of_individuals, dist_to_niche, ) ``` Select survivors from the last front by reference-vector niching (adapted from pymoo). Source code in `desdeo/emo/operators/selection.py` ``` def niching(self, f, n_remaining, niche_count, niche_of_individuals, dist_to_niche): """Select survivors from the last front by reference-vector niching (adapted from pymoo).""" survivors = [] # boolean array of elements that are considered for each iteration mask = np.full(f.shape[0], fill_value=True) while len(survivors) < n_remaining: # all niches where new individuals can be assigned to next_niches_list = np.unique(niche_of_individuals[mask]) # pick a niche with minimum assigned individuals - break tie if necessary next_niche_count = niche_count[next_niches_list] next_niche = np.where(next_niche_count == next_niche_count.min())[0] next_niche = next_niches_list[next_niche] next_niche = next_niche[self.rng.integers(0, len(next_niche))] # indices of individuals that are considered and assign to next_niche next_ind = np.where(np.logical_and(niche_of_individuals == next_niche, mask))[0] # shuffle to break random tie (equal perp. dist) or select randomly self.rng.shuffle(next_ind) # if the niche is empty, take the closest individual; otherwise take a random one (already shuffled) next_ind = next_ind[np.argmin(dist_to_niche[next_ind])] if niche_count[next_niche] == 0 else next_ind[0] mask[next_ind] = False survivors.append(int(next_ind)) niche_count[next_niche] += 1 return survivors ``` ##### state ``` state() -> Sequence[Message] ``` Return the operator's state as messages for the current verbosity level. Source code in `desdeo/emo/operators/selection.py` ``` def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.selection is None or self.selected_targets is None: return [] if self.verbosity == 1: return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), DictMessage( topic=SelectorMessageTopics.STATE, value={ "ideal": self.ideal, "nadir": self.worst_fitness, "extreme_points": self.extreme_points, "n_survive": self.n_survive, }, source=self.__class__.__name__, ), ] # verbosity == 2 if isinstance(self.selected_individuals, pl.DataFrame): message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_targets, source=self.__class__.__name__, ) return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), DictMessage( topic=SelectorMessageTopics.STATE, value={ "ideal": self.ideal, "nadir": self.worst_fitness, "extreme_points": self.extreme_points, "n_survive": self.n_survive, }, source=self.__class__.__name__, ), # Array2DMessage( # topic=SelectorMessageTopics.SELECTED_INDIVIDUALS, # value=self.selected_individuals, # source=self.__class__.__name__, # ), message, ] ``` ##### update ``` update(message: Message) -> None ``` Handle an incoming message. This operator does not react to messages. Source code in `desdeo/emo/operators/selection.py` ``` def update(self, message: Message) -> None: """Handle an incoming message. This operator does not react to messages.""" ``` #### ParameterAdaptationStrategy Bases: `StrEnum` The parameter adaptation strategies for the RVEA selector. Source code in `desdeo/emo/operators/selection.py` ``` class ParameterAdaptationStrategy(StrEnum): """The parameter adaptation strategies for the RVEA selector.""" GENERATION_BASED = "GENERATION_BASED" # Based on the current generation and the maximum generation. FUNCTION_EVALUATION_BASED = ( "FUNCTION_EVALUATION_BASED" # Based on the current function evaluation and the maximum function evaluation. ) OTHER = "OTHER" # As of yet undefined strategies. ``` #### RVEASelector Bases: `BaseDecompositionSelector` Reference Vector Guided Evolutionary Algorithm (RVEA) selection operator. Source code in `desdeo/emo/operators/selection.py` ``` class RVEASelector(BaseDecompositionSelector): """Reference Vector Guided Evolutionary Algorithm (RVEA) selection operator.""" @property def provided_topics(self): """The message topics this operator publishes, keyed by verbosity level.""" return { 0: [], 1: [ SelectorMessageTopics.STATE, ], 2: [ SelectorMessageTopics.REFERENCE_VECTORS, SelectorMessageTopics.STATE, SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, ], } @property def interested_topics(self): """The message topics this operator subscribes to.""" return [ TerminatorMessageTopics.GENERATION, TerminatorMessageTopics.MAX_GENERATIONS, TerminatorMessageTopics.EVALUATION, TerminatorMessageTopics.MAX_EVALUATIONS, ] def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, alpha: float = 2.0, parameter_adaptation_strategy: ParameterAdaptationStrategy = ParameterAdaptationStrategy.GENERATION_BASED, reference_vector_options: ReferenceVectorOptions | dict | None = None, seed: int = 0, ): """Initialize the RVEA selection operator. See the class and base class for argument details.""" if parameter_adaptation_strategy not in ParameterAdaptationStrategy: raise TypeError(f"Parameter adaptation strategy must be of Type {type(ParameterAdaptationStrategy)}") if parameter_adaptation_strategy == ParameterAdaptationStrategy.OTHER: raise ValueError("Other parameter adaptation strategies are not yet implemented.") if reference_vector_options is None: reference_vector_options = ReferenceVectorOptions() if isinstance(reference_vector_options, dict): reference_vector_options = ReferenceVectorOptions.model_validate(reference_vector_options) # Just asserting correct options for RVEA reference_vector_options.vector_type = "spherical" if reference_vector_options.adaptation_frequency == 0: warnings.warn( "Adaptation frequency was set to 0. Setting it to 100 for RVEA selector. " "Set it to 0 only if you provide preference information.", UserWarning, stacklevel=3, ) reference_vector_options.adaptation_frequency = 100 super().__init__( problem=problem, reference_vector_options=reference_vector_options, verbosity=verbosity, publisher=publisher, seed=seed, ) self.reference_vectors_gamma: np.ndarray self.numerator: float | None = None self.denominator: float | None = None # Which adaptation epoch was last acted on under an evaluation budget. self._adaptation_epoch = 0 # Whether the ideal so far was taken over infeasible members only, for # want of any feasible one. Such an ideal can be better than any # feasible design can reach, so it is replaced, not minimised into, # the moment a feasible member appears. self._ideal_is_provisional = False self.alpha = alpha self.selected_individuals: list | pl.DataFrame self.selected_targets: pl.DataFrame self.selection: list[int] self.penalty = None self.parameter_adaptation_strategy = parameter_adaptation_strategy self.adapted_reference_vectors = None def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ if isinstance(parents[0], pl.DataFrame) and isinstance(offsprings[0], pl.DataFrame): solutions = parents[0].vstack(offsprings[0]) elif isinstance(parents[0], list) and isinstance(offsprings[0], list): solutions = parents[0] + offsprings[0] else: raise TypeError("The decision variables must be either a list or a polars DataFrame, not both") if len(parents[0]) == 0: raise RuntimeError( "The parents population is empty. Cannot perform selection. This is a known unresolved issue." ) alltargets = parents[1].vstack(offsprings[1]) targets = alltargets[self.target_symbols].to_numpy() if self.constraints_symbols is None or len(self.constraints_symbols) == 0: # No constraints :) if self.ideal is None: self.ideal = np.min(targets, axis=0) else: self.ideal = np.min(np.vstack((self.ideal, np.min(targets, axis=0))), axis=0) self.nadir = np.max(targets, axis=0) if self.nadir is None else self.nadir if self.adapted_reference_vectors is None: self._adapt() selection, _ = _rvea_selection( fitness=targets, reference_vectors=self.adapted_reference_vectors, ideal=self.ideal, partial_penalty=self._partial_penalty_factor(), gamma=self.reference_vectors_gamma, ) else: # Yes constraints :( constraints = ( parents[1][self.constraints_symbols].vstack(offsprings[1][self.constraints_symbols]).to_numpy() ) feasible = (constraints <= 0).all(axis=1) # The ideal is tracked over feasible members only. A generation may have # none, at the start on a tightly constrained problem or later once the # population has contracted, and a minimum over nothing raises. Keep the # previous ideal in that case, as the nadir below already does. With no # ideal yet, take a provisional one over every member. The ideal of # infeasible members can be far better than any feasible design, and # minimising into it would carry that error through every later # generation, so the provisional ideal is replaced outright by the # first feasible one, and only then minimised into as usual. if feasible.any(): feasible_ideal = np.min(targets[feasible], axis=0) if self.ideal is None or self._ideal_is_provisional: self.ideal = feasible_ideal self._ideal_is_provisional = False else: self.ideal = np.min(np.vstack((self.ideal, feasible_ideal)), axis=0) elif self.ideal is None or self._ideal_is_provisional: self.ideal = np.min(targets, axis=0) self._ideal_is_provisional = True try: nadir = np.max(targets[feasible], axis=0) self.nadir = nadir except ValueError: # No feasible solution in current population pass # Use previous nadir if self.adapted_reference_vectors is None: self._adapt() selection, _ = _rvea_selection_constrained( fitness=targets, constraints=constraints, reference_vectors=self.adapted_reference_vectors, ideal=self.ideal, partial_penalty=self._partial_penalty_factor(), gamma=self.reference_vectors_gamma, ) self.selection = np.where(selection)[0].tolist() self.selected_individuals = solutions[self.selection] self.selected_targets = alltargets[self.selection] self.notify() return self.selected_individuals, self.selected_targets def _partial_penalty_factor(self) -> float: """Calculate and return the partial penalty factor for APD calculation. This calculation does not include the angle related terms, hence the name. If the calculated penalty is outside [0, 1], it will round it up/down to 0/1 Returns: float: The partial penalty factor """ if self.numerator is None or self.denominator is None or self.denominator == 0: raise RuntimeError("Numerator and denominator must be set before calculating the partial penalty factor.") penalty = self.numerator / self.denominator penalty = float(np.clip(penalty, 0, 1)) self.penalty = (penalty**self.alpha) * self.reference_vectors.shape[1] return self.penalty def update(self, message: Message) -> None: """Update the parameters of the RVEA APD calculation. Args: message (Message): The message to update the parameters. The message should be coming from the Terminator operator (via the Publisher). """ if not isinstance(message.topic, TerminatorMessageTopics): return if not isinstance(message.value, int): return if self.parameter_adaptation_strategy == ParameterAdaptationStrategy.GENERATION_BASED: if message.topic == TerminatorMessageTopics.GENERATION: self.numerator = message.value if ( self.reference_vector_options.adaptation_frequency > 0 and self.numerator % self.reference_vector_options.adaptation_frequency == 0 ): self._adapt() if message.topic == TerminatorMessageTopics.MAX_GENERATIONS: self.denominator = message.value elif self.parameter_adaptation_strategy == ParameterAdaptationStrategy.FUNCTION_EVALUATION_BASED: if message.topic == TerminatorMessageTopics.EVALUATION: self.numerator = message.value # The adaptation frequency is stated in generations. Under an # evaluation budget one generation is about one population of # evaluations, so adapt each time the count crosses that many # evaluations times the frequency, as the generation-based # branch adapts every frequency generations. frequency = self.reference_vector_options.adaptation_frequency if frequency > 0: every = frequency * max(int(self.reference_vector_options.number_of_vectors or 1), 1) epoch = self.numerator // every if epoch > self._adaptation_epoch: self._adaptation_epoch = epoch self._adapt() if message.topic == TerminatorMessageTopics.MAX_EVALUATIONS: self.denominator = message.value return def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.selection is None: return [] if self.verbosity == 1: return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), DictMessage( topic=SelectorMessageTopics.STATE, value={ "ideal": self.ideal, "nadir": self.nadir, "partial_penalty_factor": self._partial_penalty_factor(), }, source=self.__class__.__name__, ), ] # verbosity == 2 if isinstance(self.selected_individuals, pl.DataFrame): message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_targets, source=self.__class__.__name__, ) return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), DictMessage( topic=SelectorMessageTopics.STATE, value={ "ideal": self.ideal, "nadir": self.nadir, "partial_penalty_factor": self._partial_penalty_factor(), }, source=self.__class__.__name__, ), # DictMessage( # topic=SelectorMessageTopics.SELECTED_INDIVIDUALS, # value=self.selection[0].tolist(), # source=self.__class__.__name__, # ), message, ] def _adapt(self): self.adapted_reference_vectors = self.reference_vectors if self.ideal is not None and self.nadir is not None: for i in range(self.reference_vectors.shape[0]): self.adapted_reference_vectors[i] = self.reference_vectors[i] * (self.nadir - self.ideal) self.adapted_reference_vectors = ( self.adapted_reference_vectors / np.linalg.norm(self.adapted_reference_vectors, axis=1)[:, None] ) self.reference_vectors_gamma = np.zeros(self.adapted_reference_vectors.shape[0]) for i in range(self.adapted_reference_vectors.shape[0]): closest_angle = np.inf for j in range(self.adapted_reference_vectors.shape[0]): if i != j: angle = np.arccos( np.clip(np.dot(self.adapted_reference_vectors[i], self.adapted_reference_vectors[j]), -1.0, 1.0) ) if angle < closest_angle and angle > 0: # In cases with extreme differences in obj func ranges # sometimes, the closest reference vectors are so close that # the angle between them is 0 according to arccos (literally 0) closest_angle = angle self.reference_vectors_gamma[i] = closest_angle ``` ##### interested_topics ``` interested_topics ``` The message topics this operator subscribes to. ##### provided_topics ``` provided_topics ``` The message topics this operator publishes, keyed by verbosity level. ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, alpha: float = 2.0, parameter_adaptation_strategy: ParameterAdaptationStrategy = ParameterAdaptationStrategy.GENERATION_BASED, reference_vector_options: ReferenceVectorOptions | dict | None = None, seed: int = 0, ) ``` Initialize the RVEA selection operator. See the class and base class for argument details. Source code in `desdeo/emo/operators/selection.py` ``` def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, alpha: float = 2.0, parameter_adaptation_strategy: ParameterAdaptationStrategy = ParameterAdaptationStrategy.GENERATION_BASED, reference_vector_options: ReferenceVectorOptions | dict | None = None, seed: int = 0, ): """Initialize the RVEA selection operator. See the class and base class for argument details.""" if parameter_adaptation_strategy not in ParameterAdaptationStrategy: raise TypeError(f"Parameter adaptation strategy must be of Type {type(ParameterAdaptationStrategy)}") if parameter_adaptation_strategy == ParameterAdaptationStrategy.OTHER: raise ValueError("Other parameter adaptation strategies are not yet implemented.") if reference_vector_options is None: reference_vector_options = ReferenceVectorOptions() if isinstance(reference_vector_options, dict): reference_vector_options = ReferenceVectorOptions.model_validate(reference_vector_options) # Just asserting correct options for RVEA reference_vector_options.vector_type = "spherical" if reference_vector_options.adaptation_frequency == 0: warnings.warn( "Adaptation frequency was set to 0. Setting it to 100 for RVEA selector. " "Set it to 0 only if you provide preference information.", UserWarning, stacklevel=3, ) reference_vector_options.adaptation_frequency = 100 super().__init__( problem=problem, reference_vector_options=reference_vector_options, verbosity=verbosity, publisher=publisher, seed=seed, ) self.reference_vectors_gamma: np.ndarray self.numerator: float | None = None self.denominator: float | None = None # Which adaptation epoch was last acted on under an evaluation budget. self._adaptation_epoch = 0 # Whether the ideal so far was taken over infeasible members only, for # want of any feasible one. Such an ideal can be better than any # feasible design can reach, so it is replaced, not minimised into, # the moment a feasible member appears. self._ideal_is_provisional = False self.alpha = alpha self.selected_individuals: list | pl.DataFrame self.selected_targets: pl.DataFrame self.selection: list[int] self.penalty = None self.parameter_adaptation_strategy = parameter_adaptation_strategy self.adapted_reference_vectors = None ``` ##### \_partial_penalty_factor ``` _partial_penalty_factor() -> float ``` Calculate and return the partial penalty factor for APD calculation. ``` This calculation does not include the angle related terms, hence the name. If the calculated penalty is outside [0, 1], it will round it up/down to 0/1 ``` Returns: | Name | Type | Description | | ------- | ------- | -------------------------- | | `float` | `float` | The partial penalty factor | Source code in `desdeo/emo/operators/selection.py` ``` def _partial_penalty_factor(self) -> float: """Calculate and return the partial penalty factor for APD calculation. This calculation does not include the angle related terms, hence the name. If the calculated penalty is outside [0, 1], it will round it up/down to 0/1 Returns: float: The partial penalty factor """ if self.numerator is None or self.denominator is None or self.denominator == 0: raise RuntimeError("Numerator and denominator must be set before calculating the partial penalty factor.") penalty = self.numerator / self.denominator penalty = float(np.clip(penalty, 0, 1)) self.penalty = (penalty**self.alpha) * self.reference_vectors.shape[1] return self.penalty ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the selection operation. Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | Returns: | Type | Description | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: The selected decision variables and their objective values, targets, and constraint violations. | Source code in `desdeo/emo/operators/selection.py` ``` def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ if isinstance(parents[0], pl.DataFrame) and isinstance(offsprings[0], pl.DataFrame): solutions = parents[0].vstack(offsprings[0]) elif isinstance(parents[0], list) and isinstance(offsprings[0], list): solutions = parents[0] + offsprings[0] else: raise TypeError("The decision variables must be either a list or a polars DataFrame, not both") if len(parents[0]) == 0: raise RuntimeError( "The parents population is empty. Cannot perform selection. This is a known unresolved issue." ) alltargets = parents[1].vstack(offsprings[1]) targets = alltargets[self.target_symbols].to_numpy() if self.constraints_symbols is None or len(self.constraints_symbols) == 0: # No constraints :) if self.ideal is None: self.ideal = np.min(targets, axis=0) else: self.ideal = np.min(np.vstack((self.ideal, np.min(targets, axis=0))), axis=0) self.nadir = np.max(targets, axis=0) if self.nadir is None else self.nadir if self.adapted_reference_vectors is None: self._adapt() selection, _ = _rvea_selection( fitness=targets, reference_vectors=self.adapted_reference_vectors, ideal=self.ideal, partial_penalty=self._partial_penalty_factor(), gamma=self.reference_vectors_gamma, ) else: # Yes constraints :( constraints = ( parents[1][self.constraints_symbols].vstack(offsprings[1][self.constraints_symbols]).to_numpy() ) feasible = (constraints <= 0).all(axis=1) # The ideal is tracked over feasible members only. A generation may have # none, at the start on a tightly constrained problem or later once the # population has contracted, and a minimum over nothing raises. Keep the # previous ideal in that case, as the nadir below already does. With no # ideal yet, take a provisional one over every member. The ideal of # infeasible members can be far better than any feasible design, and # minimising into it would carry that error through every later # generation, so the provisional ideal is replaced outright by the # first feasible one, and only then minimised into as usual. if feasible.any(): feasible_ideal = np.min(targets[feasible], axis=0) if self.ideal is None or self._ideal_is_provisional: self.ideal = feasible_ideal self._ideal_is_provisional = False else: self.ideal = np.min(np.vstack((self.ideal, feasible_ideal)), axis=0) elif self.ideal is None or self._ideal_is_provisional: self.ideal = np.min(targets, axis=0) self._ideal_is_provisional = True try: nadir = np.max(targets[feasible], axis=0) self.nadir = nadir except ValueError: # No feasible solution in current population pass # Use previous nadir if self.adapted_reference_vectors is None: self._adapt() selection, _ = _rvea_selection_constrained( fitness=targets, constraints=constraints, reference_vectors=self.adapted_reference_vectors, ideal=self.ideal, partial_penalty=self._partial_penalty_factor(), gamma=self.reference_vectors_gamma, ) self.selection = np.where(selection)[0].tolist() self.selected_individuals = solutions[self.selection] self.selected_targets = alltargets[self.selection] self.notify() return self.selected_individuals, self.selected_targets ``` ##### state ``` state() -> Sequence[Message] ``` Return the operator's state as messages for the current verbosity level. Source code in `desdeo/emo/operators/selection.py` ``` def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.selection is None: return [] if self.verbosity == 1: return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), DictMessage( topic=SelectorMessageTopics.STATE, value={ "ideal": self.ideal, "nadir": self.nadir, "partial_penalty_factor": self._partial_penalty_factor(), }, source=self.__class__.__name__, ), ] # verbosity == 2 if isinstance(self.selected_individuals, pl.DataFrame): message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_targets, source=self.__class__.__name__, ) return [ Array2DMessage( topic=SelectorMessageTopics.REFERENCE_VECTORS, value=self.reference_vectors.tolist(), source=self.__class__.__name__, ), DictMessage( topic=SelectorMessageTopics.STATE, value={ "ideal": self.ideal, "nadir": self.nadir, "partial_penalty_factor": self._partial_penalty_factor(), }, source=self.__class__.__name__, ), # DictMessage( # topic=SelectorMessageTopics.SELECTED_INDIVIDUALS, # value=self.selection[0].tolist(), # source=self.__class__.__name__, # ), message, ] ``` ##### update ``` update(message: Message) -> None ``` Update the parameters of the RVEA APD calculation. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------------------------------------------------------------------------------- | ---------- | | `message` | `Message` | The message to update the parameters. The message should be coming from the Terminator operator (via the Publisher). | *required* | Source code in `desdeo/emo/operators/selection.py` ``` def update(self, message: Message) -> None: """Update the parameters of the RVEA APD calculation. Args: message (Message): The message to update the parameters. The message should be coming from the Terminator operator (via the Publisher). """ if not isinstance(message.topic, TerminatorMessageTopics): return if not isinstance(message.value, int): return if self.parameter_adaptation_strategy == ParameterAdaptationStrategy.GENERATION_BASED: if message.topic == TerminatorMessageTopics.GENERATION: self.numerator = message.value if ( self.reference_vector_options.adaptation_frequency > 0 and self.numerator % self.reference_vector_options.adaptation_frequency == 0 ): self._adapt() if message.topic == TerminatorMessageTopics.MAX_GENERATIONS: self.denominator = message.value elif self.parameter_adaptation_strategy == ParameterAdaptationStrategy.FUNCTION_EVALUATION_BASED: if message.topic == TerminatorMessageTopics.EVALUATION: self.numerator = message.value # The adaptation frequency is stated in generations. Under an # evaluation budget one generation is about one population of # evaluations, so adapt each time the count crosses that many # evaluations times the frequency, as the generation-based # branch adapts every frequency generations. frequency = self.reference_vector_options.adaptation_frequency if frequency > 0: every = frequency * max(int(self.reference_vector_options.number_of_vectors or 1), 1) epoch = self.numerator // every if epoch > self._adaptation_epoch: self._adaptation_epoch = epoch self._adapt() if message.topic == TerminatorMessageTopics.MAX_EVALUATIONS: self.denominator = message.value return ``` #### ReferenceVectorOptions Bases: `BaseModel` Pydantic model for Reference Vector arguments. Source code in `desdeo/emo/operators/selection.py` ``` class ReferenceVectorOptions(BaseModel): """Pydantic model for Reference Vector arguments.""" model_config = ConfigDict(use_attribute_docstrings=True) adaptation_frequency: int = Field(default=0) """Number of generations between reference vector adaptation. If set to 0, no adaptation occurs. Defaults to 0. Only used if no preference is provided.""" creation_type: Literal["simplex", "s_energy"] = Field(default="simplex") """The method for creating reference vectors. Defaults to "simplex". If set to "simplex", the reference vectors are created using the simplex lattice design method. This method is generates distributions with specific numbers of reference vectors. Check: https://www.itl.nist.gov/div898/handbook/pri/section5/pri542.htm for more information. If set to "s_energy", the reference vectors are created using the Riesz s-energy criterion. This method is used to distribute an arbitrary number of reference vectors in the objective space while minimizing the s-energy. """ vector_type: Literal["spherical", "planar"] = Field(default="spherical") """The method for normalizing the reference vectors. Defaults to "spherical".""" lattice_resolution: int | None = None """Number of divisions along an axis when creating the simplex lattice. This is not required/used for the "s_energy" method. If not specified, the lattice resolution is calculated based on the `number_of_vectors`. If "spherical" is selected as the `vector_type`, this value overrides the `number_of_vectors`. """ number_of_vectors: int = 200 """Number of reference vectors to be created. If "simplex" is selected as the `creation_type`, then the closest `lattice_resolution` is calculated based on this value. If "s_energy" is selected, then this value is used directly. Note that if neither `lattice_resolution` nor `number_of_vectors` is specified, the number of vectors defaults to 200. Overridden if "spherical" is selected as the `vector_type` and `lattice_resolution` is provided. """ adaptation_distance: float = Field(default=0.2) """Distance parameter for the interactive adaptation methods. Defaults to 0.2.""" reference_point: dict[str, float] | None = Field(default=None) """The reference point for interactive adaptation.""" preferred_solutions: dict[str, list[float]] | None = Field(default=None) """The preferred solutions for interactive adaptation.""" non_preferred_solutions: dict[str, list[float]] | None = Field(default=None) """The non-preferred solutions for interactive adaptation.""" preferred_ranges: dict[str, list[float]] | None = Field(default=None) """The preferred ranges for interactive adaptation.""" ``` ##### adaptation_distance ``` adaptation_distance: float = Field(default=0.2) ``` Distance parameter for the interactive adaptation methods. Defaults to 0.2. ##### adaptation_frequency ``` adaptation_frequency: int = Field(default=0) ``` Number of generations between reference vector adaptation. If set to 0, no adaptation occurs. Defaults to 0. Only used if no preference is provided. ##### creation_type ``` creation_type: Literal["simplex", "s_energy"] = Field( default="simplex" ) ``` The method for creating reference vectors. Defaults to "simplex". If set to "simplex", the reference vectors are created using the simplex lattice design method. This method is generates distributions with specific numbers of reference vectors. Check: https://www.itl.nist.gov/div898/handbook/pri/section5/pri542.htm for more information. If set to "s_energy", the reference vectors are created using the Riesz s-energy criterion. This method is used to distribute an arbitrary number of reference vectors in the objective space while minimizing the s-energy. ##### lattice_resolution ``` lattice_resolution: int | None = None ``` Number of divisions along an axis when creating the simplex lattice. This is not required/used for the "s_energy" method. If not specified, the lattice resolution is calculated based on the `number_of_vectors`. If "spherical" is selected as the `vector_type`, this value overrides the `number_of_vectors`. ##### non_preferred_solutions ``` non_preferred_solutions: dict[str, list[float]] | None = ( Field(default=None) ) ``` The non-preferred solutions for interactive adaptation. ##### number_of_vectors ``` number_of_vectors: int = 200 ``` Number of reference vectors to be created. If "simplex" is selected as the `creation_type`, then the closest `lattice_resolution` is calculated based on this value. If "s_energy" is selected, then this value is used directly. Note that if neither `lattice_resolution` nor `number_of_vectors` is specified, the number of vectors defaults to 200. Overridden if "spherical" is selected as the `vector_type` and `lattice_resolution` is provided. ##### preferred_ranges ``` preferred_ranges: dict[str, list[float]] | None = Field( default=None ) ``` The preferred ranges for interactive adaptation. ##### preferred_solutions ``` preferred_solutions: dict[str, list[float]] | None = Field( default=None ) ``` The preferred solutions for interactive adaptation. ##### reference_point ``` reference_point: dict[str, float] | None = Field( default=None ) ``` The reference point for interactive adaptation. ##### vector_type ``` vector_type: Literal["spherical", "planar"] = Field( default="spherical" ) ``` The method for normalizing the reference vectors. Defaults to "spherical". #### SMSEMOASelector Bases: `BaseSelector` Implements the selection operator defined for SMSEMOA. Implements the selection operator defined for SMSEMOA, which included the hypervolume contribution calculation. Beume, N., Naujoks, B., & Emmerich, M. (2007). SMS-EMOA: Multiobjective selection based on dominated hypervolume. European Journal of Operational Research, 181(3), 1653-1669. https://doi.org/10.1016/j.ejor.2006.08.008 Source code in `desdeo/emo/operators/selection.py` ``` class SMSEMOASelector(BaseSelector): """Implements the selection operator defined for SMSEMOA. Implements the selection operator defined for SMSEMOA, which included the hypervolume contribution calculation. Beume, N., Naujoks, B., & Emmerich, M. (2007). SMS-EMOA: Multiobjective selection based on dominated hypervolume. European Journal of Operational Research, 181(3), 1653-1669. https://doi.org/10.1016/j.ejor.2006.08.008 """ @property def provided_topics(self): """The message topics this operator publishes, keyed by verbosity level.""" return { 0: [], 1: [SelectorMessageTopics.STATE], 2: [ SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, SelectorMessageTopics.STATE, ], } @property def interested_topics(self): """The message topics this operator subscribes to.""" return [] def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, normalised_reference_point_component: float, seed: int = 0, ): """Initialize the SMS-EMOA selection operator. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. normalised_reference_point_component (float, optional): The reference point component used for hypervolume calculation. The solutions are normalized to the range [0, 1] and the reference point is set to a vector of ones multiplied by this component. seed (int, optional): The random seed to use. Defaults to 0. """ super().__init__( problem, verbosity=verbosity, publisher=publisher, seed=seed, ) self.selection: list[int] | None = None self.selected_individuals: SolutionType | None = None self.selected_targets: pl.DataFrame | None = None if normalised_reference_point_component < 1: raise ValueError("The reference point component must be greater than or equal to 1.") self.reference_point_component = normalised_reference_point_component self.removed: int = 0 def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ if isinstance(parents[0], pl.DataFrame) and isinstance(offsprings[0], pl.DataFrame): solutions = parents[0].vstack(offsprings[0]) elif isinstance(parents[0], list) and isinstance(offsprings[0], list): solutions = parents[0] + offsprings[0] else: raise TypeError("The decision variables must be either a list or a polars DataFrame, not both") alltargets = parents[1].vstack(offsprings[1]) if self.constraints_symbols is None or len(self.constraints_symbols) == 0: # No constraints, use SMS-EMOA selection self.removed = self._sms_emoa_selection(alltargets[self.target_symbols].to_numpy()) elif not (alltargets.select(self.constraints_symbols) > 0).to_numpy().any(): # All offsprings are feasible self.removed = self._sms_emoa_selection(alltargets[self.target_symbols].to_numpy()) else: # Some offsprings are infeasible. Remove the most infeasible offspring. violations = ( alltargets[self.constraints_symbols].to_numpy(), alltargets.select(self.constraints_symbols).to_numpy(), ) self.removed = int(np.argmax(np.sum(np.maximum(0, violations), axis=1))) self.selection = list(range(len(alltargets))) self.selection.remove(self.removed) if isinstance(solutions, pl.DataFrame) and self.selection is not None: self.selected_individuals = solutions[self.selection] elif isinstance(solutions, list) and self.selection is not None: self.selected_individuals = [solutions[i] for i in self.selection] else: raise RuntimeError("Something went wrong with the selection") self.selected_targets = alltargets[self.selection] self.notify() return self.selected_individuals, self.selected_targets def _sms_emoa_selection(self, targets: np.ndarray) -> int: """Perform the SMS-EMOA selection operation. Note that in the paper in Algorithm 2, the factor (totalHV - currentHV) is minimized. As totalHV is constant, this is equivalent to maximizing currentHV, which is what we do here. Args: targets (np.ndarray): The objective values of the individuals. Returns: int: The index of the individual to be removed. """ fronts = fast_non_dominated_sort_indices(targets) last_front = fronts[-1] if len(last_front) == 1: return last_front[0] # last front has more than one individual, compute hypervolume contributions max_hv = -np.inf worst_index = -1 targets = targets - np.min(targets, axis=0) # shift to origin targets = targets / np.max(targets, axis=0) # scale to [0, 1] (based on the whole population) # using moocore hv contribusions hv_contribs = hv_contributions( targets[last_front], ref=np.ones(targets.shape[1]) * self.reference_point_component ) min_contrib_index = np.argmin(hv_contribs) return last_front[min_contrib_index] for i in last_front: remaining_front = [j for j in last_front if j != i] current_hv = hv(targets[remaining_front], reference_point_component=self.reference_point_component) if current_hv > max_hv: max_hv = current_hv worst_index = i return worst_index def update(self, message: Message) -> None: """Handle an incoming message. This operator does not react to messages.""" def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.selection is None or self.selected_targets is None: return [] if self.verbosity == 1: return [ DictMessage( topic=SelectorMessageTopics.STATE, value={ "selection": self.selection, "removed": self.removed, }, source=self.__class__.__name__, ) ] # verbosity == 2 if isinstance(self.selected_individuals, pl.DataFrame): message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_targets, source=self.__class__.__name__, ) return [ DictMessage( topic=SelectorMessageTopics.STATE, value={ "selection": self.selection, "removed": self.removed, }, source=self.__class__.__name__, ), message, ] ``` ##### interested_topics ``` interested_topics ``` The message topics this operator subscribes to. ##### provided_topics ``` provided_topics ``` The message topics this operator publishes, keyed by verbosity level. ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, normalised_reference_point_component: float, seed: int = 0, ) ``` Initialize the SMS-EMOA selection operator. Parameters: | Name | Type | Description | Default | | -------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The optimization problem to be solved. | *required* | | `verbosity` | `int` | The verbosity level of the operator. | *required* | | `publisher` | `Publisher` | The publisher to use for communication. | *required* | | `normalised_reference_point_component` | `float` | The reference point component used for hypervolume calculation. The solutions are normalized to the range [0, 1] and the reference point is set to a vector of ones multiplied by this component. | *required* | | `seed` | `int` | The random seed to use. Defaults to 0. | `0` | Source code in `desdeo/emo/operators/selection.py` ``` def __init__( self, problem: Problem, verbosity: int, publisher: Publisher, normalised_reference_point_component: float, seed: int = 0, ): """Initialize the SMS-EMOA selection operator. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. normalised_reference_point_component (float, optional): The reference point component used for hypervolume calculation. The solutions are normalized to the range [0, 1] and the reference point is set to a vector of ones multiplied by this component. seed (int, optional): The random seed to use. Defaults to 0. """ super().__init__( problem, verbosity=verbosity, publisher=publisher, seed=seed, ) self.selection: list[int] | None = None self.selected_individuals: SolutionType | None = None self.selected_targets: pl.DataFrame | None = None if normalised_reference_point_component < 1: raise ValueError("The reference point component must be greater than or equal to 1.") self.reference_point_component = normalised_reference_point_component self.removed: int = 0 ``` ##### \_sms_emoa_selection ``` _sms_emoa_selection(targets: ndarray) -> int ``` Perform the SMS-EMOA selection operation. Note that in the paper in Algorithm 2, the factor (totalHV - currentHV) is minimized. As totalHV is constant, this is equivalent to maximizing currentHV, which is what we do here. Parameters: | Name | Type | Description | Default | | --------- | --------- | ---------------------------------------- | ---------- | | `targets` | `ndarray` | The objective values of the individuals. | *required* | Returns: | Name | Type | Description | | ----- | ----- | ------------------------------------------ | | `int` | `int` | The index of the individual to be removed. | Source code in `desdeo/emo/operators/selection.py` ``` def _sms_emoa_selection(self, targets: np.ndarray) -> int: """Perform the SMS-EMOA selection operation. Note that in the paper in Algorithm 2, the factor (totalHV - currentHV) is minimized. As totalHV is constant, this is equivalent to maximizing currentHV, which is what we do here. Args: targets (np.ndarray): The objective values of the individuals. Returns: int: The index of the individual to be removed. """ fronts = fast_non_dominated_sort_indices(targets) last_front = fronts[-1] if len(last_front) == 1: return last_front[0] # last front has more than one individual, compute hypervolume contributions max_hv = -np.inf worst_index = -1 targets = targets - np.min(targets, axis=0) # shift to origin targets = targets / np.max(targets, axis=0) # scale to [0, 1] (based on the whole population) # using moocore hv contribusions hv_contribs = hv_contributions( targets[last_front], ref=np.ones(targets.shape[1]) * self.reference_point_component ) min_contrib_index = np.argmin(hv_contribs) return last_front[min_contrib_index] for i in last_front: remaining_front = [j for j in last_front if j != i] current_hv = hv(targets[remaining_front], reference_point_component=self.reference_point_component) if current_hv > max_hv: max_hv = current_hv worst_index = i return worst_index ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the selection operation. Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | Returns: | Type | Description | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: The selected decision variables and their objective values, targets, and constraint violations. | Source code in `desdeo/emo/operators/selection.py` ``` def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame], ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: parents (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. offsprings (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their objective values, targets, and constraint violations. """ if isinstance(parents[0], pl.DataFrame) and isinstance(offsprings[0], pl.DataFrame): solutions = parents[0].vstack(offsprings[0]) elif isinstance(parents[0], list) and isinstance(offsprings[0], list): solutions = parents[0] + offsprings[0] else: raise TypeError("The decision variables must be either a list or a polars DataFrame, not both") alltargets = parents[1].vstack(offsprings[1]) if self.constraints_symbols is None or len(self.constraints_symbols) == 0: # No constraints, use SMS-EMOA selection self.removed = self._sms_emoa_selection(alltargets[self.target_symbols].to_numpy()) elif not (alltargets.select(self.constraints_symbols) > 0).to_numpy().any(): # All offsprings are feasible self.removed = self._sms_emoa_selection(alltargets[self.target_symbols].to_numpy()) else: # Some offsprings are infeasible. Remove the most infeasible offspring. violations = ( alltargets[self.constraints_symbols].to_numpy(), alltargets.select(self.constraints_symbols).to_numpy(), ) self.removed = int(np.argmax(np.sum(np.maximum(0, violations), axis=1))) self.selection = list(range(len(alltargets))) self.selection.remove(self.removed) if isinstance(solutions, pl.DataFrame) and self.selection is not None: self.selected_individuals = solutions[self.selection] elif isinstance(solutions, list) and self.selection is not None: self.selected_individuals = [solutions[i] for i in self.selection] else: raise RuntimeError("Something went wrong with the selection") self.selected_targets = alltargets[self.selection] self.notify() return self.selected_individuals, self.selected_targets ``` ##### state ``` state() -> Sequence[Message] ``` Return the operator's state as messages for the current verbosity level. Source code in `desdeo/emo/operators/selection.py` ``` def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.selection is None or self.selected_targets is None: return [] if self.verbosity == 1: return [ DictMessage( topic=SelectorMessageTopics.STATE, value={ "selection": self.selection, "removed": self.removed, }, source=self.__class__.__name__, ) ] # verbosity == 2 if isinstance(self.selected_individuals, pl.DataFrame): message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_targets, source=self.__class__.__name__, ) return [ DictMessage( topic=SelectorMessageTopics.STATE, value={ "selection": self.selection, "removed": self.removed, }, source=self.__class__.__name__, ), message, ] ``` ##### update ``` update(message: Message) -> None ``` Handle an incoming message. This operator does not react to messages. Source code in `desdeo/emo/operators/selection.py` ``` def update(self, message: Message) -> None: """Handle an incoming message. This operator does not react to messages.""" ``` #### SPEA2Selector Bases: `_FitnessPublishingSelector` The environmental selection of SPEA2, which fills the archive. Every solution of the archive and the population with a fitness below one, that is every nondominated solution, is copied to the next archive. If they do not fill it, the best dominated solutions by fitness complete it; if they overfill it, `spea2_truncate` thins them. The archive is what this selector returns, and the fitness it publishes is `1 / (1 + F)`, higher-is-better and positive, for the binary tournament that mates within the archive. Under template 2 the parents passed to `do` are the archive and the offspring are the population, so the archive size is `population_size` and the population size is the mating selection's `winner_size`. In the first generation the archive is empty and the initial population is passed as the parents, which is the same thing. The paper has no constraint handling for continuous problems. On a constrained problem the strengths and raw fitness use constrained domination (Deb et al. 2002), so that feasible solutions are the nondominated ones whenever there are any. This is DESDEO's addition. References Zitzler, E., Laumanns, M., & Thiele, L. (2001). SPEA2: Improving the strength Pareto evolutionary algorithm. TIK-Report 103, Computer Engineering and Networks Laboratory (TIK), ETH Zurich. https://doi.org/10.3929/ethz-a-004284029 Source code in `desdeo/emo/operators/selection.py` ``` class SPEA2Selector(_FitnessPublishingSelector): """The environmental selection of SPEA2, which fills the archive. Every solution of the archive and the population with a fitness below one, that is every nondominated solution, is copied to the next archive. If they do not fill it, the best dominated solutions by fitness complete it; if they overfill it, `spea2_truncate` thins them. The archive is what this selector returns, and the fitness it publishes is `1 / (1 + F)`, higher-is-better and positive, for the binary tournament that mates within the archive. Under template 2 the parents passed to `do` are the archive and the offspring are the population, so the archive size is `population_size` and the population size is the mating selection's `winner_size`. In the first generation the archive is empty and the initial population is passed as the parents, which is the same thing. The paper has no constraint handling for continuous problems. On a constrained problem the strengths and raw fitness use constrained domination (Deb et al. 2002), so that feasible solutions are the nondominated ones whenever there are any. This is DESDEO's addition. References: Zitzler, E., Laumanns, M., & Thiele, L. (2001). SPEA2: Improving the strength Pareto evolutionary algorithm. TIK-Report 103, Computer Engineering and Networks Laboratory (TIK), ETH Zurich. https://doi.org/10.3929/ethz-a-004284029 """ def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Select the next archive from the current archive and population. Args: parents (tuple[SolutionType, pl.DataFrame]): the archive (or the initial population) and its outputs. offsprings (tuple[SolutionType, pl.DataFrame]): the population and its outputs. Empty in the first generation. Returns: tuple[SolutionType, pl.DataFrame]: the next archive and its outputs. """ solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy().astype(float) violations = total_constraint_violation(outputs, self.constraints_symbols) fitness, distances = spea2_fitness(targets, violations) nondominated = np.flatnonzero(fitness < 1) if len(nondominated) > self.population_size: kept = spea2_truncate(distances[np.ix_(nondominated, nondominated)], self.population_size) chosen = nondominated[kept] else: dominated = np.flatnonzero(fitness >= 1) best_dominated = dominated[np.argsort(fitness[dominated], kind="stable")] chosen = np.concatenate([nondominated, best_dominated[: self.population_size - len(nondominated)]]) chosen = chosen.tolist() return self._finish(solutions, outputs, chosen, 1.0 / (1.0 + fitness[chosen])) ``` ##### do ``` do( parents: tuple[SolutionType, DataFrame], offsprings: tuple[SolutionType, DataFrame], ) -> tuple[SolutionType, pl.DataFrame] ``` Select the next archive from the current archive and population. Parameters: | Name | Type | Description | Default | | ------------ | -------------------------------- | -------------------------------------------------------------- | ---------- | | `parents` | `tuple[SolutionType, DataFrame]` | the archive (or the initial population) and its outputs. | *required* | | `offsprings` | `tuple[SolutionType, DataFrame]` | the population and its outputs. Empty in the first generation. | *required* | Returns: | Type | Description | | -------------------------------- | ---------------------------------------------------------------------- | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: the next archive and its outputs. | Source code in `desdeo/emo/operators/selection.py` ``` def do( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[SolutionType, pl.DataFrame]: """Select the next archive from the current archive and population. Args: parents (tuple[SolutionType, pl.DataFrame]): the archive (or the initial population) and its outputs. offsprings (tuple[SolutionType, pl.DataFrame]): the population and its outputs. Empty in the first generation. Returns: tuple[SolutionType, pl.DataFrame]: the next archive and its outputs. """ solutions, outputs = self._merge(parents, offsprings) targets = outputs[self.target_symbols].to_numpy().astype(float) violations = total_constraint_violation(outputs, self.constraints_symbols) fitness, distances = spea2_fitness(targets, violations) nondominated = np.flatnonzero(fitness < 1) if len(nondominated) > self.population_size: kept = spea2_truncate(distances[np.ix_(nondominated, nondominated)], self.population_size) chosen = nondominated[kept] else: dominated = np.flatnonzero(fitness >= 1) best_dominated = dominated[np.argsort(fitness[dominated], kind="stable")] chosen = np.concatenate([nondominated, best_dominated[: self.population_size - len(nondominated)]]) chosen = chosen.tolist() return self._finish(solutions, outputs, chosen, 1.0 / (1.0 + fitness[chosen])) ``` #### \_FitnessPublishingSelector Bases: `BaseSelector` Shared state publishing for selectors that feed a mating tournament through SELECTED_FITNESS. Source code in `desdeo/emo/operators/selection.py` ``` class _FitnessPublishingSelector(BaseSelector): """Shared state publishing for selectors that feed a mating tournament through SELECTED_FITNESS.""" @property def provided_topics(self): """The message topics this operator publishes, keyed by verbosity level.""" return { 0: [], 1: [SelectorMessageTopics.STATE], 2: [SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, SelectorMessageTopics.SELECTED_FITNESS], } @property def interested_topics(self): """The message topics this operator subscribes to.""" return [] def __init__(self, problem: Problem, verbosity: int, publisher: Publisher, population_size: int, seed: int = 0): """Initialize the selector. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. population_size (int): The number of solutions selected each generation. seed (int, optional): The random seed to use. Defaults to 0. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if population_size < 1: raise ValueError("population_size must be positive.") self.population_size = population_size self.selection: list[int] | None = None self.selected_individuals: SolutionType | None = None self.selected_targets: pl.DataFrame | None = None self.fitness: np.ndarray | None = None def _merge( self, parents: tuple[SolutionType, pl.DataFrame], offsprings: tuple[SolutionType, pl.DataFrame] ) -> tuple[pl.DataFrame, pl.DataFrame]: if not isinstance(parents[0], pl.DataFrame): raise TypeError(f"{self.__class__.__name__} works on polars DataFrames only.") if offsprings[1].is_empty(): return parents[0], parents[1] return parents[0].vstack(offsprings[0]), parents[1].vstack(offsprings[1]) def _finish(self, solutions: pl.DataFrame, outputs: pl.DataFrame, chosen: list[int], fitness: np.ndarray): self.selection = chosen self.selected_individuals = solutions[chosen] self.selected_targets = outputs[chosen] self.fitness = fitness self.notify() return self.selected_individuals, self.selected_targets def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.selection is None or self.selected_targets is None: return [] state = DictMessage( topic=SelectorMessageTopics.STATE, value={"population_size": self.population_size, "selected_individuals": self.selection}, source=self.__class__.__name__, ) if self.verbosity == 1: return [state] return [ state, PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ), NumpyArrayMessage( topic=SelectorMessageTopics.SELECTED_FITNESS, value=self.fitness, source=self.__class__.__name__, ), ] def update(self, message: Message) -> None: """Handle an incoming message. This operator does not react to messages.""" ``` ##### interested_topics ``` interested_topics ``` The message topics this operator subscribes to. ##### provided_topics ``` provided_topics ``` The message topics this operator publishes, keyed by verbosity level. ##### __init__ ``` __init__( problem: Problem, verbosity: int, publisher: Publisher, population_size: int, seed: int = 0, ) ``` Initialize the selector. Parameters: | Name | Type | Description | Default | | ----------------- | ----------- | ------------------------------------------------- | ---------- | | `problem` | `Problem` | The optimization problem to be solved. | *required* | | `verbosity` | `int` | The verbosity level of the operator. | *required* | | `publisher` | `Publisher` | The publisher to use for communication. | *required* | | `population_size` | `int` | The number of solutions selected each generation. | *required* | | `seed` | `int` | The random seed to use. Defaults to 0. | `0` | Source code in `desdeo/emo/operators/selection.py` ``` def __init__(self, problem: Problem, verbosity: int, publisher: Publisher, population_size: int, seed: int = 0): """Initialize the selector. Args: problem (Problem): The optimization problem to be solved. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to use for communication. population_size (int): The number of solutions selected each generation. seed (int, optional): The random seed to use. Defaults to 0. """ super().__init__(problem=problem, verbosity=verbosity, publisher=publisher, seed=seed) if population_size < 1: raise ValueError("population_size must be positive.") self.population_size = population_size self.selection: list[int] | None = None self.selected_individuals: SolutionType | None = None self.selected_targets: pl.DataFrame | None = None self.fitness: np.ndarray | None = None ``` ##### state ``` state() -> Sequence[Message] ``` Return the operator's state as messages for the current verbosity level. Source code in `desdeo/emo/operators/selection.py` ``` def state(self) -> Sequence[Message]: """Return the operator's state as messages for the current verbosity level.""" if self.verbosity == 0 or self.selection is None or self.selected_targets is None: return [] state = DictMessage( topic=SelectorMessageTopics.STATE, value={"population_size": self.population_size, "selected_individuals": self.selection}, source=self.__class__.__name__, ) if self.verbosity == 1: return [state] return [ state, PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ), NumpyArrayMessage( topic=SelectorMessageTopics.SELECTED_FITNESS, value=self.fitness, source=self.__class__.__name__, ), ] ``` ##### update ``` update(message: Message) -> None ``` Handle an incoming message. This operator does not react to messages. Source code in `desdeo/emo/operators/selection.py` ``` def update(self, message: Message) -> None: """Handle an incoming message. This operator does not react to messages.""" ``` #### \_hype_exact_3d ``` _hype_exact_3d( points: ndarray, reference: ndarray, weights: ndarray ) -> np.ndarray ``` Exact `I_h^k` of every point in three objectives, by sweeping the third objective. Within each slab between consecutive values of the third objective, the cells of the grid spanned by the first two objectives' values are dominated by a known number `d` of the points added so far; each such cell's volume times `weights[d]` goes to every point dominating it, which a suffix sum over the grid delivers. The cost is cubic in the number of points. Source code in `desdeo/emo/operators/selection.py` ``` @njit def _hype_exact_3d(points: np.ndarray, reference: np.ndarray, weights: np.ndarray) -> np.ndarray: """Exact `I_h^k` of every point in three objectives, by sweeping the third objective. Within each slab between consecutive values of the third objective, the cells of the grid spanned by the first two objectives' values are dominated by a known number `d` of the points added so far; each such cell's volume times `weights[d]` goes to every point dominating it, which a suffix sum over the grid delivers. The cost is cubic in the number of points. """ n = points.shape[0] xs = np.unique(np.append(points[:, 0], reference[0])) ys = np.unique(np.append(points[:, 1], reference[1])) nx, ny = len(xs) - 1, len(ys) - 1 ix = np.searchsorted(xs, points[:, 0]) iy = np.searchsorted(ys, points[:, 1]) order = np.argsort(points[:, 2]) counts = np.zeros((nx + 1, ny + 1), dtype=np.int64) suffix = np.zeros((nx + 1, ny + 1)) values = np.zeros(n) added = 0 while added < n: z_low = points[order[added], 2] while added < n and points[order[added], 2] == z_low: q = order[added] for i in range(ix[q], nx): for j in range(iy[q], ny): counts[i, j] += 1 added += 1 z_high = points[order[added], 2] if added < n else reference[2] height = z_high - z_low if height <= 0: continue for i in range(nx - 1, -1, -1): for j in range(ny - 1, -1, -1): count = counts[i, j] cell = weights[count] * (xs[i + 1] - xs[i]) * (ys[j + 1] - ys[j]) * height if count > 0 else 0.0 suffix[i, j] = cell + suffix[i + 1, j] + suffix[i, j + 1] - suffix[i + 1, j + 1] for u in range(added): q = order[u] values[q] += suffix[ix[q], iy[q]] return values ``` #### \_hype_monte_carlo_hits ``` _hype_monte_carlo_hits( points: ndarray, samples: ndarray, weights: ndarray, k: int, ) -> np.ndarray ``` Sum `weights[d]` over the samples each point dominates, `d` being the sample's dominator count. A sample with more than `k` dominators credits nobody, so counting stops there. Source code in `desdeo/emo/operators/selection.py` ``` @njit def _hype_monte_carlo_hits(points: np.ndarray, samples: np.ndarray, weights: np.ndarray, k: int) -> np.ndarray: """Sum `weights[d]` over the samples each point dominates, `d` being the sample's dominator count. A sample with more than `k` dominators credits nobody, so counting stops there. """ n, m = points.shape values = np.zeros(n) dominators = np.empty(n, dtype=np.int64) for s in range(samples.shape[0]): count = 0 for a in range(n): dominates = True for j in range(m): if points[a, j] > samples[s, j]: dominates = False break if dominates: dominators[count] = a count += 1 if count > k: break if 0 < count <= k: weight = weights[count] for u in range(count): values[dominators[u]] += weight return values ``` #### \_ibea_fitness ``` _ibea_fitness( fitness_components: ndarray, kappa: float ) -> np.ndarray ``` Calculates the IBEA fitness for each individual based on pairwise fitness components. Parameters: | Name | Type | Description | Default | | -------------------- | --------- | --------------------------------------------------- | ---------- | | `fitness_components` | `ndarray` | The pairwise fitness components of the individuals. | *required* | | `kappa` | `float` | The kappa value for the IBEA selection. | *required* | Returns: | Type | Description | | --------- | -------------------------------------------------------- | | `ndarray` | np.ndarray: The IBEA fitness values for each individual. | Source code in `desdeo/emo/operators/selection.py` ``` @njit def _ibea_fitness(fitness_components: np.ndarray, kappa: float) -> np.ndarray: """Calculates the IBEA fitness for each individual based on pairwise fitness components. Args: fitness_components (np.ndarray): The pairwise fitness components of the individuals. kappa (float): The kappa value for the IBEA selection. Returns: np.ndarray: The IBEA fitness values for each individual. """ num_individuals = fitness_components.shape[0] fitness = np.zeros(num_individuals) for i in range(num_individuals): for j in range(num_individuals): if i != j: fitness[i] -= np.exp(-fitness_components[j, i] / kappa) return fitness ``` #### \_ibea_select ``` _ibea_select( fitness_components: ndarray, bad_sols: ndarray, kappa: float, ) -> int ``` Selects the worst individual based on the IBEA indicator. Parameters: | Name | Type | Description | Default | | -------------------- | --------- | ------------------------------------------------------------------ | ---------- | | `fitness_components` | `ndarray` | The pairwise fitness components of the individuals. | *required* | | `bad_sols` | `ndarray` | A boolean array indicating which individuals are considered "bad". | *required* | | `kappa` | `float` | The kappa value for the IBEA selection. | *required* | Returns: | Name | Type | Description | | ----- | ----- | ------------------------------------- | | `int` | `int` | The index of the selected individual. | Source code in `desdeo/emo/operators/selection.py` ``` @njit def _ibea_select(fitness_components: np.ndarray, bad_sols: np.ndarray, kappa: float) -> int: """Selects the worst individual based on the IBEA indicator. Args: fitness_components (np.ndarray): The pairwise fitness components of the individuals. bad_sols (np.ndarray): A boolean array indicating which individuals are considered "bad". kappa (float): The kappa value for the IBEA selection. Returns: int: The index of the selected individual. """ fitness = np.zeros(len(fitness_components)) for i in range(len(fitness_components)): if bad_sols[i]: continue for j in range(len(fitness_components)): if bad_sols[j] or i == j: continue fitness[i] -= np.exp(-fitness_components[j, i] / kappa) choice = np.argmin(fitness) if fitness[choice] >= 0: if sum(bad_sols) == len(fitness_components) - 1: # If all but one individual is chosen, select the last one return np.where(~bad_sols)[0][0] raise RuntimeError("All individuals have non-negative fitness. Cannot select a new individual.") return choice ``` #### \_ibea_select_all ``` _ibea_select_all( fitness_components: ndarray, population_size: int, kappa: float, ) -> np.ndarray ``` Selects all individuals based on the IBEA indicator. Parameters: | Name | Type | Description | Default | | -------------------- | --------- | --------------------------------------------------- | ---------- | | `fitness_components` | `ndarray` | The pairwise fitness components of the individuals. | *required* | | `population_size` | `int` | The desired size of the population after selection. | *required* | | `kappa` | `float` | The kappa value for the IBEA selection. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------- | | `ndarray` | list\[int\]: The list of indices of the selected individuals. | Source code in `desdeo/emo/operators/selection.py` ``` @njit def _ibea_select_all(fitness_components: np.ndarray, population_size: int, kappa: float) -> np.ndarray: """Selects all individuals based on the IBEA indicator. Args: fitness_components (np.ndarray): The pairwise fitness components of the individuals. population_size (int): The desired size of the population after selection. kappa (float): The kappa value for the IBEA selection. Returns: list[int]: The list of indices of the selected individuals. """ current_pop_size = len(fitness_components) bad_sols = np.zeros(current_pop_size, dtype=np.bool_) fitness = np.zeros(len(fitness_components)) mod_fit_components = np.exp(-fitness_components / kappa) for i in range(len(fitness_components)): for j in range(len(fitness_components)): if i == j: continue fitness[i] -= mod_fit_components[j, i] while current_pop_size - sum(bad_sols) > population_size: selected = np.argmin(fitness) if fitness[selected] >= 0: if sum(bad_sols) == len(fitness_components) - 1: # If all but one individual is chosen, select the last one selected = np.where(~bad_sols)[0][0] raise RuntimeError("All individuals have non-negative fitness. Cannot select a new individual.") fitness[selected] = np.inf # Make sure that this individual is not selected again bad_sols[selected] = True for i in range(len(mod_fit_components)): if bad_sols[i]: continue # Update fitness of the remaining individuals fitness[i] += mod_fit_components[selected, i] return ~bad_sols ``` #### \_lp_norm ``` _lp_norm(points: ndarray, p: float) -> np.ndarray ``` `||x||_p` along the last axis; the largest absolute value when `p` is infinite, as MATLAB's `vecnorm`. Source code in `desdeo/emo/operators/selection.py` ``` def _lp_norm(points: np.ndarray, p: float) -> np.ndarray: """`||x||_p` along the last axis; the largest absolute value when `p` is infinite, as MATLAB's `vecnorm`.""" with np.errstate(all="ignore"): if np.isinf(p): return np.max(np.abs(points), axis=-1) return np.sum(np.abs(points) ** p, axis=-1) ** (1.0 / p) ``` #### \_nan_argmax ``` _nan_argmax(values: ndarray) -> int ``` Index of the largest value skipping NaN, or 0 when every value is NaN, as MATLAB's `max` returns it. Source code in `desdeo/emo/operators/selection.py` ``` def _nan_argmax(values: np.ndarray) -> int: """Index of the largest value skipping NaN, or 0 when every value is NaN, as MATLAB's `max` returns it.""" return 0 if np.isnan(values).all() else int(np.nanargmax(values)) ``` #### \_nan_argmin ``` _nan_argmin(values: ndarray) -> int ``` Index of the smallest value skipping NaN, or 0 when every value is NaN, as MATLAB's `min` returns it. Source code in `desdeo/emo/operators/selection.py` ``` def _nan_argmin(values: np.ndarray) -> int: """Index of the smallest value skipping NaN, or 0 when every value is NaN, as MATLAB's `min` returns it.""" return 0 if np.isnan(values).all() else int(np.nanargmin(values)) ``` #### \_nsga2_crowding_distance_assignment ``` _nsga2_crowding_distance_assignment( non_dominated_front: ndarray, f_mins: ndarray, f_maxs: ndarray, ) -> np.ndarray ``` Computes the crowding distance as pecified in the definition of NSGA2. This function computed the crowding distances for a non-dominated set of solutions. A smaller value means that a solution is more crowded (worse), while a larger value means it is less crowded (better). Note The boundary point in `non_dominated_front` will be assigned a non-crowding distance value of `np.inf` indicating, that they shouls always be included in later sorting. Parameters: | Name | Type | Description | Default | | --------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `non_dominated_front` | `ndarray` | a 2D numpy array (size n x m = number of vectors x number of targets (obejctive funcitons)) containing mutually non-dominated vectors. The values of the vectors correspond to the optimization 'target' (usually the minimized objective function values.) | *required* | | `f_mins` | `ndarray` | a 1D numpy array of size m containing the minimum objective function values in non_dominated_front. | *required* | | `f_maxs` | `ndarray` | a 1D numpy array of size m containing the maximum objective function values in non_dominated_front. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: a numpy array of size m containing the crowding distances for each vector in non_dominated_front. | Deb, K., Pratap, A., Agarwal, S., & Meyarivan, T. A. M. T. (2002). A fast and elitist multiobjective genetic algorithm: NSGA-II. IEEE transactions on evolutionary computation, 6(2), 182-197. Source code in `desdeo/emo/operators/selection.py` ``` @njit def _nsga2_crowding_distance_assignment( non_dominated_front: np.ndarray, f_mins: np.ndarray, f_maxs: np.ndarray ) -> np.ndarray: """Computes the crowding distance as pecified in the definition of NSGA2. This function computed the crowding distances for a non-dominated set of solutions. A smaller value means that a solution is more crowded (worse), while a larger value means it is less crowded (better). Note: The boundary point in `non_dominated_front` will be assigned a non-crowding distance value of `np.inf` indicating, that they shouls always be included in later sorting. Args: non_dominated_front (np.ndarray): a 2D numpy array (size n x m = number of vectors x number of targets (obejctive funcitons)) containing mutually non-dominated vectors. The values of the vectors correspond to the optimization 'target' (usually the minimized objective function values.) f_mins (np.ndarray): a 1D numpy array of size m containing the minimum objective function values in `non_dominated_front`. f_maxs (np.ndarray): a 1D numpy array of size m containing the maximum objective function values in `non_dominated_front`. Returns: np.ndarray: a numpy array of size m containing the crowding distances for each vector in `non_dominated_front`. Reference: Deb, K., Pratap, A., Agarwal, S., & Meyarivan, T. A. M. T. (2002). A fast and elitist multiobjective genetic algorithm: NSGA-II. IEEE transactions on evolutionary computation, 6(2), 182-197. """ vectors = non_dominated_front # I num_vectors = vectors.shape[0] # l num_objectives = vectors.shape[1] crowding_distances = np.zeros(num_vectors) # I[i]_distance for m in range(num_objectives): # An objective that is constant across the whole population separates nothing. Sorting by it # gives an arbitrary order, so marking its two ends as boundary points would hand an infinite # distance to two arbitrary solutions, and the normalisation below would divide by zero. if f_maxs[m] == f_mins[m]: continue # sort by column (objective) m_order = vectors[:, m].argsort() # inlcude boundary points crowding_distances[m_order[0]], crowding_distances[m_order[-1]] = np.inf, np.inf for i in range(1, num_vectors - 1): crowding_distances[m_order[i]] = crowding_distances[m_order[i]] + ( vectors[m_order[i + 1], m] - vectors[m_order[i - 1], m] ) / (f_maxs[m] - f_mins[m]) return crowding_distances ``` #### \_rvea_selection ``` _rvea_selection( fitness: ndarray, reference_vectors: ndarray, ideal: ndarray, partial_penalty: float, gamma: ndarray, ) -> tuple[np.ndarray, np.ndarray] ``` Select individuals based on their fitness and their distance to the reference vectors. Parameters: | Name | Type | Description | Default | | ------------------- | --------- | ------------------------------------------------------- | ---------- | | `fitness` | `ndarray` | The fitness values of the individuals. | *required* | | `reference_vectors` | `ndarray` | The reference vectors. | *required* | | `ideal` | `ndarray` | The ideal point. | *required* | | `partial_penalty` | `float` | The partial penalty in APD. | *required* | | `gamma` | `ndarray` | The angle between current and closest reference vector. | *required* | Returns: | Type | Description | | ------------------------- | --------------------------------------------------------------------------------------- | | `tuple[ndarray, ndarray]` | tuple\[np.ndarray, np.ndarray\]: The selected individuals and their APD fitness values. | Source code in `desdeo/emo/operators/selection.py` ``` @njit def _rvea_selection( fitness: np.ndarray, reference_vectors: np.ndarray, ideal: np.ndarray, partial_penalty: float, gamma: np.ndarray ) -> tuple[np.ndarray, np.ndarray]: """Select individuals based on their fitness and their distance to the reference vectors. Args: fitness (np.ndarray): The fitness values of the individuals. reference_vectors (np.ndarray): The reference vectors. ideal (np.ndarray): The ideal point. partial_penalty (float): The partial penalty in APD. gamma (np.ndarray): The angle between current and closest reference vector. Returns: tuple[np.ndarray, np.ndarray]: The selected individuals and their APD fitness values. """ tranlated_fitness = fitness - ideal num_vectors = reference_vectors.shape[0] num_solutions = fitness.shape[0] cos_matrix = np.zeros((num_solutions, num_vectors)) for i in range(num_solutions): solution = tranlated_fitness[i] norm = np.linalg.norm(solution) for j in range(num_vectors): cos_matrix[i, j] = np.dot(solution, reference_vectors[j]) / max(1e-10, norm) # Avoid division by zero assignment_matrix = np.zeros((num_solutions, num_vectors), dtype=np.bool_) for i in range(num_solutions): assignment_matrix[i, np.argmax(cos_matrix[i])] = True selection = np.zeros(num_solutions, dtype=np.bool_) apd_fitness = np.zeros(num_solutions, dtype=np.float64) for j in range(num_vectors): min_apd = np.inf select = -1 for i in np.where(assignment_matrix[:, j])[0]: solution = tranlated_fitness[i] apd = (1 + (partial_penalty * np.arccos(cos_matrix[i, j]) / gamma[j])) * np.linalg.norm(solution) apd_fitness[i] = apd if apd < min_apd: min_apd = apd select = i # A reference vector with no associated solution leaves select at -1. Guarding here is # essential: selection[-1] = True would silently promote the *last* individual in the array, # once per empty vector. Empty vectors are common, and become commoner as the number of # objectives grows, so the unguarded write biases selection exactly where RVEA is used most. if select != -1: selection[select] = True return selection, apd_fitness ``` #### \_rvea_selection_constrained ``` _rvea_selection_constrained( fitness: ndarray, constraints: ndarray, reference_vectors: ndarray, ideal: ndarray, partial_penalty: float, gamma: ndarray, ) -> tuple[np.ndarray, np.ndarray] ``` Select individuals based on their fitness and their distance to the reference vectors. Parameters: | Name | Type | Description | Default | | ------------------- | --------- | ------------------------------------------------------- | ---------- | | `fitness` | `ndarray` | The fitness values of the individuals. | *required* | | `constraints` | `ndarray` | The constraint violations of the individuals. | *required* | | `reference_vectors` | `ndarray` | The reference vectors. | *required* | | `ideal` | `ndarray` | The ideal point. | *required* | | `partial_penalty` | `float` | The partial penalty in APD. | *required* | | `gamma` | `ndarray` | The angle between current and closest reference vector. | *required* | Returns: | Type | Description | | ------------------------- | --------------------------------------------------------------------------------------- | | `tuple[ndarray, ndarray]` | tuple\[np.ndarray, np.ndarray\]: The selected individuals and their APD fitness values. | Source code in `desdeo/emo/operators/selection.py` ``` @njit def _rvea_selection_constrained( fitness: np.ndarray, constraints: np.ndarray, reference_vectors: np.ndarray, ideal: np.ndarray, partial_penalty: float, gamma: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: """Select individuals based on their fitness and their distance to the reference vectors. Args: fitness (np.ndarray): The fitness values of the individuals. constraints (np.ndarray): The constraint violations of the individuals. reference_vectors (np.ndarray): The reference vectors. ideal (np.ndarray): The ideal point. partial_penalty (float): The partial penalty in APD. gamma (np.ndarray): The angle between current and closest reference vector. Returns: tuple[np.ndarray, np.ndarray]: The selected individuals and their APD fitness values. """ tranlated_fitness = fitness - ideal num_vectors = reference_vectors.shape[0] num_solutions = fitness.shape[0] violations = np.maximum(0, constraints) cos_matrix = np.zeros((num_solutions, num_vectors)) for i in range(num_solutions): solution = tranlated_fitness[i] norm = np.linalg.norm(solution) for j in range(num_vectors): cos_matrix[i, j] = np.dot(solution, reference_vectors[j]) / max(1e-10, norm) # Avoid division by zero assignment_matrix = np.zeros((num_solutions, num_vectors), dtype=np.bool_) for i in range(num_solutions): assignment_matrix[i, np.argmax(cos_matrix[i])] = True selection = np.zeros(num_solutions, dtype=np.bool_) apd_fitness = np.zeros(num_solutions, dtype=np.float64) for j in range(num_vectors): min_apd = np.inf min_violation = np.inf select = -1 select_violation = -1 for i in np.where(assignment_matrix[:, j])[0]: solution = tranlated_fitness[i] apd = (1 + (partial_penalty * np.arccos(cos_matrix[i, j]) / gamma[j])) * np.linalg.norm(solution) apd_fitness[i] = apd feasible = np.all(violations[i] == 0) current_violation = np.sum(violations[i]) if feasible: if apd < min_apd: min_apd = apd select = i elif current_violation < min_violation: min_violation = current_violation select_violation = i if select != -1: selection[select] = True elif select_violation != -1: # Guarding this branch matters as much as the one above: a reference vector with no # associated solution at all leaves both indices at -1, and selection[-1] = True would # silently promote the last individual in the array, once per empty vector. selection[select_violation] = True return selection, apd_fitness ``` #### \_sorts_before ``` _sorts_before(a: float, b: float) -> bool ``` True when `a` comes before `b` in ascending order, with NaN last as in `np.sort`. Source code in `desdeo/emo/operators/selection.py` ``` @njit def _sorts_before(a: float, b: float) -> bool: """True when `a` comes before `b` in ascending order, with NaN last as in `np.sort`.""" return a < b or (np.isnan(b) and not np.isnan(a)) ``` #### \_spea2_truncate ``` _spea2_truncate( distances: ndarray, keep: int ) -> np.ndarray ``` The loop of `spea2_truncate`, returning the kept positions in ascending order. Each row's candidates are sorted by distance once. Removing a candidate deletes it from every row, which leaves the rows sorted, so no row is sorted again. Source code in `desdeo/emo/operators/selection.py` ``` @njit def _spea2_truncate(distances: np.ndarray, keep: int) -> np.ndarray: """The loop of `spea2_truncate`, returning the kept positions in ascending order. Each row's candidates are sorted by distance once. Removing a candidate deletes it from every row, which leaves the rows sorted, so no row is sorted again. """ n = len(distances) neighbours = np.empty((n, n), dtype=np.int64) for i in range(n): neighbours[i] = np.argsort(distances[i]) alive = np.ones(n, dtype=np.bool_) size = n while size > keep: # The lexicographically smallest row of sorted distances; the first one wins a tie. crowded = -1 for i in range(n): if not alive[i]: continue if crowded == -1: crowded = i continue for j in range(size): current = distances[i, neighbours[i, j]] best = distances[crowded, neighbours[crowded, j]] if _sorts_before(current, best): crowded = i break if _sorts_before(best, current): break alive[crowded] = False for i in range(n): if not alive[i]: continue j = 0 while neighbours[i, j] != crowded: j += 1 for t in range(j, size - 1): neighbours[i, t] = neighbours[i, t + 1] size -= 1 return np.flatnonzero(alive) ``` #### agemoea2_corner_solutions ``` agemoea2_corner_solutions(front: ndarray) -> np.ndarray ``` The point nearest each objective axis by perpendicular distance (`FindCornerSolutions` in the author's code). A point can be the corner of several axes. When the front has no more points than objectives, every point is a corner. Source code in `desdeo/emo/operators/selection.py` ``` def agemoea2_corner_solutions(front: np.ndarray) -> np.ndarray: """The point nearest each objective axis by perpendicular distance (`FindCornerSolutions` in the author's code). A point can be the corner of several axes. When the front has no more points than objectives, every point is a corner. """ m, n = front.shape if m <= n: return np.arange(m) with np.errstate(all="ignore"): return np.array([_nan_argmin(np.linalg.norm(np.delete(front, i, axis=1), axis=1)) for i in range(n)]) ``` #### agemoea2_curvature ``` agemoea2_curvature( point: ndarray, tolerance: float = 0.001, max_iterations: int = 100, ) -> float ``` Estimate the exponent `p` with `sum_i a_i ** p = 1` by Newton-Raphson (Panichella 2022, Eq. 7-9). Starts from `p = 1` and stops when two iterates differ by at most `tolerance` (Section 3.1). Coordinates equal to zero are left out of the derivative, the paper's convention `0 ** p * log 0 = 0`. A result that is NaN or not positive is replaced by 1, a flat front, as `ComputeGeometry` in the author's code does. Eq. 9 is printed as `p + log(S) / D`, with `S = sum a ** p` and `D = sum a ** p log a`. That sign sends the iteration the wrong way: on the paper's own example B = (cos pi/8, sin pi/8) it reaches -1.44 after four steps. Newton's step for `f(p) = log S` is `p - f / f' = p - S log(S) / D`, which the author's code takes and which reaches the paper's reported 1.999999999879 in four steps. Source code in `desdeo/emo/operators/selection.py` ``` def agemoea2_curvature(point: np.ndarray, tolerance: float = 1e-3, max_iterations: int = 100) -> float: """Estimate the exponent `p` with `sum_i a_i ** p = 1` by Newton-Raphson (Panichella 2022, Eq. 7-9). Starts from `p = 1` and stops when two iterates differ by at most `tolerance` (Section 3.1). Coordinates equal to zero are left out of the derivative, the paper's convention `0 ** p * log 0 = 0`. A result that is NaN or not positive is replaced by 1, a flat front, as `ComputeGeometry` in the author's code does. Eq. 9 is printed as `p + log(S) / D`, with `S = sum a ** p` and `D = sum a ** p log a`. That sign sends the iteration the wrong way: on the paper's own example B = (cos pi/8, sin pi/8) it reaches -1.44 after four steps. Newton's step for `f(p) = log S` is `p - f / f' = p - S log(S) / D`, which the author's code takes and which reaches the paper's reported 1.999999999879 in four steps. """ nonzero = point[point != 0] p = previous = 1.0 with np.errstate(all="ignore"): for _ in range(max_iterations): powered = nonzero**p p -= np.log(np.sum(point**p)) * np.sum(powered) / np.sum(powered * np.log(nonzero)) if abs(p - previous) <= tolerance: break previous = p return 1.0 if np.isnan(p) or p <= 0 else float(abs(p)) ``` #### agemoea2_extreme_points ``` agemoea2_extreme_points(front: ndarray) -> np.ndarray ``` The extreme points AGE-MOEA-II normalizes a shifted first front by (`front_normalization` in the author's code). For each objective, the point that minimizes the achievement scalarizing function with weight 1 on that objective and 1e-6 on the others, as in NSGA-III. One point can be the extreme of several objectives. Source code in `desdeo/emo/operators/selection.py` ``` def agemoea2_extreme_points(front: np.ndarray) -> np.ndarray: """The extreme points AGE-MOEA-II normalizes a shifted first front by (`front_normalization` in the author's code). For each objective, the point that minimizes the achievement scalarizing function with weight 1 on that objective and 1e-6 on the others, as in NSGA-III. One point can be the extreme of several objectives. """ weights = 1e-6 + np.eye(front.shape[1]) with np.errstate(all="ignore"): return np.array([_nan_argmin(np.fmax.reduce(front / w, axis=1)) for w in weights]) ``` #### agemoea2_geodesic_distances ``` agemoea2_geodesic_distances( front: ndarray, p: float ) -> np.ndarray ``` Approximate geodesic distances between the projections of a normalized front (Panichella 2022, Sec. 3.2). Each point is projected onto the manifold `sum_i x_i ** p = 1` (Eq. 14). The distance between two projected points is the length of the two-segment path through the projection of their midpoint (Eq. 11-13). On a flat front (p = 1) the midpoint already lies on the manifold, and the path is the straight segment. Source code in `desdeo/emo/operators/selection.py` ``` def agemoea2_geodesic_distances(front: np.ndarray, p: float) -> np.ndarray: """Approximate geodesic distances between the projections of a normalized front (Panichella 2022, Sec. 3.2). Each point is projected onto the manifold `sum_i x_i ** p = 1` (Eq. 14). The distance between two projected points is the length of the two-segment path through the projection of their midpoint (Eq. 11-13). On a flat front (p = 1) the midpoint already lies on the manifold, and the path is the straight segment. """ with np.errstate(all="ignore"): projected = front / np.sum(front**p, axis=1, keepdims=True) ** (1.0 / p) midpoints = (projected[:, None, :] + projected[None, :, :]) / 2 midpoints = midpoints / np.sum(midpoints**p, axis=2, keepdims=True) ** (1.0 / p) distances = np.linalg.norm(projected[:, None, :] - midpoints, axis=2) + np.linalg.norm( projected[None, :, :] - midpoints, axis=2 ) np.fill_diagonal(distances, 0.0) return distances ``` #### agemoea2_normalize ``` agemoea2_normalize( front: ndarray, ) -> tuple[np.ndarray, np.ndarray] ``` Normalize a first front shifted to its ideal point (Panichella 2019, Section 3.2, as the author's code does it). Each objective is divided by the intercept of the hyperplane through the extreme points (`agemoea2_extreme_points`), and the result is shifted so that each objective's smallest value is zero again. The largest value of each objective replaces the intercepts only when one of them is NaN, so a negative or infinite intercept is kept, although the paper falls back to these min-max constants whenever the plane is "indefinite, impossible or leading to abnormal normalization results". The plane is solved by LU factorization, as MATLAB's backslash solves a square system, so a singular one gives Inf or NaN instead of an error. Returns: | Type | Description | | ------------------------- | -------------------------------------------------------------------------------------------- | | `tuple[ndarray, ndarray]` | tuple\[np.ndarray, np.ndarray\]: the normalized front and the indices of the extreme points. | Source code in `desdeo/emo/operators/selection.py` ``` def agemoea2_normalize(front: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Normalize a first front shifted to its ideal point (Panichella 2019, Section 3.2, as the author's code does it). Each objective is divided by the intercept of the hyperplane through the extreme points (`agemoea2_extreme_points`), and the result is shifted so that each objective's smallest value is zero again. The largest value of each objective replaces the intercepts only when one of them is NaN, so a negative or infinite intercept is kept, although the paper falls back to these min-max constants whenever the plane is "indefinite, impossible or leading to abnormal normalization results". The plane is solved by LU factorization, as MATLAB's backslash solves a square system, so a singular one gives Inf or NaN instead of an error. Returns: tuple[np.ndarray, np.ndarray]: the normalized front and the indices of the extreme points. """ extremes = agemoea2_extreme_points(front) with np.errstate(all="ignore"), warnings.catch_warnings(): warnings.simplefilter("ignore", LinAlgWarning) plane = lu_solve(lu_factor(front[extremes], check_finite=False), np.ones(front.shape[1]), check_finite=False) intercepts = 1.0 / plane if np.isnan(intercepts).any(): intercepts = np.fmax.reduce(front, axis=0) with np.errstate(all="ignore"): normalized = front / intercepts return normalized - np.fmin.reduce(normalized, axis=0), extremes ``` #### agemoea2_survival_score ``` agemoea2_survival_score( front: ndarray, ) -> tuple[np.ndarray, float] ``` The survival scores of a first front and its curvature (Panichella 2019, Algorithm 2, lines 2-18). The front is shifted to its ideal point and normalized (`agemoea2_normalize`), and the curvature `p` is estimated on the solution nearest the origin that is not a corner (`agemoea2_corner_solutions`, `agemoea2_curvature`). The extreme points score infinity. The rest join the selected set one at a time, each time the one whose diversity (the sum of its two smallest geodesic distances to the selected set) divided by its proximity (`||f||_p`) is largest, and that ratio is its score. As in the author's code, the last solution left keeps the score 0. Returns: | Type | Description | | ----------------------- | --------------------------------------------------------------------- | | `tuple[ndarray, float]` | tuple\[np.ndarray, float\]: the scores, in the order of front, and p. | Source code in `desdeo/emo/operators/selection.py` ``` def agemoea2_survival_score(front: np.ndarray) -> tuple[np.ndarray, float]: """The survival scores of a first front and its curvature (Panichella 2019, Algorithm 2, lines 2-18). The front is shifted to its ideal point and normalized (`agemoea2_normalize`), and the curvature `p` is estimated on the solution nearest the origin that is not a corner (`agemoea2_corner_solutions`, `agemoea2_curvature`). The extreme points score infinity. The rest join the selected set one at a time, each time the one whose diversity (the sum of its two smallest geodesic distances to the selected set) divided by its proximity (`||f||_p`) is largest, and that ratio is its score. As in the author's code, the last solution left keeps the score 0. Returns: tuple[np.ndarray, float]: the scores, in the order of `front`, and `p`. """ score = np.zeros(len(front)) with np.errstate(all="ignore"): normalized, extremes = agemoea2_normalize(front - np.fmin.reduce(front, axis=0)) score[extremes] = np.inf selected = np.zeros(len(front), dtype=bool) selected[extremes] = True nearest = np.linalg.norm(normalized, axis=1) nearest[agemoea2_corner_solutions(normalized)] = np.inf p = agemoea2_curvature(normalized[_nan_argmin(nearest)]) with np.errstate(all="ignore"): distances = agemoea2_geodesic_distances(normalized, p) / _lp_norm(normalized, p)[:, None] remaining = list(np.flatnonzero(~selected)) for _ in range(len(remaining) - 1): # np.sort puts NaN last, as MATLAB's mink does. value = np.sort(distances[np.ix_(remaining, np.flatnonzero(selected))], axis=1)[:, :2].sum(axis=1) best = _nan_argmax(value) score[remaining[best]] = value[best] selected[remaining.pop(best)] = True return score, p ``` #### constrained_dominance_matrix ``` constrained_dominance_matrix( targets: ndarray, violations: ndarray | None ) -> np.ndarray ``` `dom[i, j]` is True when solution i dominates solution j under constrained domination. A feasible solution dominates every infeasible one, of two infeasible solutions the one with the smaller total violation dominates, and two feasible solutions are compared by Pareto dominance (Deb et al. 2002). Without constraints this is Pareto dominance. Source code in `desdeo/emo/operators/selection.py` ``` def constrained_dominance_matrix(targets: np.ndarray, violations: np.ndarray | None) -> np.ndarray: """`dom[i, j]` is True when solution i dominates solution j under constrained domination. A feasible solution dominates every infeasible one, of two infeasible solutions the one with the smaller total violation dominates, and two feasible solutions are compared by Pareto dominance (Deb et al. 2002). Without constraints this is Pareto dominance. """ dominance = dominance_matrix(targets) if violations is None: return dominance feasible = violations <= 0 # Basically, feasible solutions dominate infeasible ones, and among infeasible solutions the one with # the smaller violation "dominates". Feasible solutions are compared by Pareto dominance. return np.where(feasible[:, None] & feasible[None, :], dominance, violations[:, None] < violations[None, :]) ``` #### hype_alpha ``` hype_alpha(k: int, size: int) -> np.ndarray ``` The weights `alpha_i / i` of HypE's fitness `I_h^k` for a set of `size` solutions (Bader and Zitzler, Eq. 12-13). `alpha_i = prod_{j=1}^{i-1} (k - j) / (size - j)` is the probability that a region dominated by `i` solutions is lost when `k` solutions are removed at random, given that one of them is removed. Returns: | Type | Description | | --------- | --------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: weights[i] = alpha_i / i for i = 0..size, with weights[0] = 0 and zero for i > k. | Source code in `desdeo/emo/operators/selection.py` ``` def hype_alpha(k: int, size: int) -> np.ndarray: """The weights `alpha_i / i` of HypE's fitness `I_h^k` for a set of `size` solutions (Bader and Zitzler, Eq. 12-13). `alpha_i = prod_{j=1}^{i-1} (k - j) / (size - j)` is the probability that a region dominated by `i` solutions is lost when `k` solutions are removed at random, given that one of them is removed. Returns: np.ndarray: `weights[i] = alpha_i / i` for `i = 0..size`, with `weights[0] = 0` and zero for `i > k`. """ weights = np.zeros(size + 1) alpha = 1.0 for i in range(1, min(k, size) + 1): if i > 1: alpha *= (k - (i - 1)) / (size - (i - 1)) weights[i] = alpha / i return weights ``` #### hype_fitness_exact ``` hype_fitness_exact( points: ndarray, reference: ndarray, k: int ) -> np.ndarray ``` Exact HypE fitness `I_h^k(a, A, R)` of every point for two or three objectives (Bader and Zitzler, Def. III.6). Parameters: | Name | Type | Description | Default | | ----------- | --------- | --------------------------------------------------------------------- | ---------- | | `points` | `ndarray` | the minimized objective vectors of the set A, shape (n, m), m 2 or 3. | *required* | | `reference` | `ndarray` | the reference point, shape (m,). | *required* | | `k` | `int` | the fitness parameter, the number of solutions to be removed. | *required* | Returns: | Type | Description | | --------- | -------------------------------------- | | `ndarray` | np.ndarray: the fitness of each point. | Source code in `desdeo/emo/operators/selection.py` ``` def hype_fitness_exact(points: np.ndarray, reference: np.ndarray, k: int) -> np.ndarray: """Exact HypE fitness `I_h^k(a, A, R)` of every point for two or three objectives (Bader and Zitzler, Def. III.6). Args: points (np.ndarray): the minimized objective vectors of the set `A`, shape `(n, m)`, `m` 2 or 3. reference (np.ndarray): the reference point, shape `(m,)`. k (int): the fitness parameter, the number of solutions to be removed. Returns: np.ndarray: the fitness of each point. """ n, m = points.shape if m not in (2, 3): raise ValueError("Exact HypE fitness is implemented for two and three objectives.") clipped = np.minimum(points, reference) if m == 2: # noqa: PLR2004 clipped = np.column_stack([clipped, np.zeros(n)]) reference = np.append(reference, 1.0) return _hype_exact_3d(clipped.astype(float), np.asarray(reference, dtype=float), hype_alpha(k, n)) ``` #### hype_fitness_monte_carlo ``` hype_fitness_monte_carlo( points: ndarray, reference: ndarray, k: int, n_samples: int, rng: Generator, ) -> np.ndarray ``` Monte Carlo estimate of the HypE fitness `I_h^k` (Bader and Zitzler, Algorithm 3). Samples are drawn uniformly from the box between the points' minimum and the reference point. Each sample dominated by `d <= k` points credits each of them `weights[d]` times the box volume over the number of samples. Source code in `desdeo/emo/operators/selection.py` ``` def hype_fitness_monte_carlo( points: np.ndarray, reference: np.ndarray, k: int, n_samples: int, rng: np.random.Generator ) -> np.ndarray: """Monte Carlo estimate of the HypE fitness `I_h^k` (Bader and Zitzler, Algorithm 3). Samples are drawn uniformly from the box between the points' minimum and the reference point. Each sample dominated by `d <= k` points credits each of them `weights[d]` times the box volume over the number of samples. """ lower = points.min(axis=0) span = np.maximum(reference - lower, 0.0) samples = lower + span * rng.random((n_samples, points.shape[1])) hits = _hype_monte_carlo_hits(points.astype(float), samples, hype_alpha(k, len(points)), k) return hits * float(np.prod(span)) / n_samples ``` #### jitted_calc_perpendicular_distance ``` jitted_calc_perpendicular_distance( solutions: ndarray, ref_dirs: ndarray, invert_reference_vectors: bool, ) -> np.ndarray ``` Calculate the perpendicular distance between solutions and reference directions. Parameters: | Name | Type | Description | Default | | -------------------------- | --------- | ---------------------------------------- | ---------- | | `solutions` | `ndarray` | The normalized solutions. | *required* | | `ref_dirs` | `ndarray` | The reference directions. | *required* | | `invert_reference_vectors` | `bool` | Whether to invert the reference vectors. | *required* | Returns: | Type | Description | | --------- | ---------------------------------------------- | | `ndarray` | np.ndarray: The perpendicular distance matrix. | Source code in `desdeo/emo/operators/selection.py` ``` @njit def jitted_calc_perpendicular_distance( solutions: np.ndarray, ref_dirs: np.ndarray, invert_reference_vectors: bool ) -> np.ndarray: """Calculate the perpendicular distance between solutions and reference directions. Args: solutions (np.ndarray): The normalized solutions. ref_dirs (np.ndarray): The reference directions. invert_reference_vectors (bool): Whether to invert the reference vectors. Returns: np.ndarray: The perpendicular distance matrix. """ matrix = np.zeros((solutions.shape[0], ref_dirs.shape[0])) for i in range(ref_dirs.shape[0]): for j in range(solutions.shape[0]): if invert_reference_vectors: unit_vector = 1 - ref_dirs[i] unit_vector = -unit_vector / np.linalg.norm(unit_vector) else: unit_vector = ref_dirs[i] / np.linalg.norm(ref_dirs[i]) component = ref_dirs[i] - solutions[j] - np.dot(ref_dirs[i] - solutions[j], unit_vector) * unit_vector matrix[j, i] = np.linalg.norm(component) return matrix ``` #### modified_wasfga_asf ``` modified_wasfga_asf( targets: ndarray, reference_points: ndarray, weights: ndarray, ideal: ndarray, nadir: ndarray, rho: float, ) -> np.ndarray ``` The normalised achievement scalarizing function of WASF-GA's reference code. `s = max_i mu_i d_i + rho sum_i d_i`, with `d_i = (f_i - q_i) / (nadir_i - ideal_i)`, as `AchievementScalarizingFunction.evaluateNormalizing` computes it. The augmentation term is not weighted by `mu`, unlike eq. (2) of the papers. An objective whose range is zero is divided by one instead. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | --------------------------------------------------------------- | ---------- | | `targets` | `ndarray` | The minimised objective vectors, one per row (n x k). | *required* | | `reference_points` | `ndarray` | The reference point of each weight vector, one per row (m x k). | *required* | | `weights` | `ndarray` | The weight vectors, one per row (m x k). | *required* | | `ideal` | `ndarray` | The ideal point used for normalisation (k). | *required* | | `nadir` | `ndarray` | The nadir point used for normalisation (k). | *required* | | `rho` | `float` | The augmentation coefficient. | *required* | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------- | | `ndarray` | np.ndarray: The ASF value of every solution for every weight vector (n x m). | Source code in `desdeo/emo/operators/selection.py` ``` def modified_wasfga_asf( targets: np.ndarray, reference_points: np.ndarray, weights: np.ndarray, ideal: np.ndarray, nadir: np.ndarray, rho: float, ) -> np.ndarray: """The normalised achievement scalarizing function of WASF-GA's reference code. `s = max_i mu_i d_i + rho sum_i d_i`, with `d_i = (f_i - q_i) / (nadir_i - ideal_i)`, as `AchievementScalarizingFunction.evaluateNormalizing` computes it. The augmentation term is not weighted by `mu`, unlike eq. (2) of the papers. An objective whose range is zero is divided by one instead. Args: targets (np.ndarray): The minimised objective vectors, one per row (n x k). reference_points (np.ndarray): The reference point of each weight vector, one per row (m x k). weights (np.ndarray): The weight vectors, one per row (m x k). ideal (np.ndarray): The ideal point used for normalisation (k). nadir (np.ndarray): The nadir point used for normalisation (k). rho (float): The augmentation coefficient. Returns: np.ndarray: The ASF value of every solution for every weight vector (n x m). """ span = nadir - ideal span = np.where(span > 0, span, 1.0) differences = (targets[:, None, :] - reference_points[None, :, :]) / span return (weights[None, :, :] * differences).max(axis=2) + rho * differences.sum(axis=2) ``` #### modified_wasfga_weights ``` modified_wasfga_weights( n_objectives: int, number_of_weights: int, epsilon: float, ) -> np.ndarray ``` The weight vectors of (Modified) WASF-GA, whose inverses are spread over the simplex. The reference code generates well-spread vectors `u` with every component at least `epsilon`, inverts them and normalises the result to sum to one, `mu_i = (1 / u_i) / sum_j (1 / u_j)` (WASF-GA eq. 4, `Weights.invertWeights(weights, true)`). With two objectives `u` is uniform, `u_1 = epsilon + j (1 - 2 epsilon) / (N_mu - 1)` and `u_2 = 1 - u_1` (`initUniformPairAndOddWeights2D`). With more, the code reads a fixed simplex lattice from a file, which its loader cannot parse; here `number_of_weights` s-energy vectors are shrunk affinely onto the part of the simplex where every component is at least `epsilon`, which maps the simplex's corners to the corners of those files. Parameters: | Name | Type | Description | Default | | ------------------- | ------- | ---------------------------------- | ---------- | | `n_objectives` | `int` | The number of objectives k. | *required* | | `number_of_weights` | `int` | The number of weight vectors N_mu. | *required* | | `epsilon` | `float` | The smallest component of u. | *required* | Returns: | Type | Description | | --------- | ----------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: The weight vectors mu, one per row, in the order the fronts visit them. | Source code in `desdeo/emo/operators/selection.py` ``` def modified_wasfga_weights(n_objectives: int, number_of_weights: int, epsilon: float) -> np.ndarray: """The weight vectors of (Modified) WASF-GA, whose inverses are spread over the simplex. The reference code generates well-spread vectors `u` with every component at least `epsilon`, inverts them and normalises the result to sum to one, `mu_i = (1 / u_i) / sum_j (1 / u_j)` (WASF-GA eq. 4, `Weights.invertWeights(weights, true)`). With two objectives `u` is uniform, `u_1 = epsilon + j (1 - 2 epsilon) / (N_mu - 1)` and `u_2 = 1 - u_1` (`initUniformPairAndOddWeights2D`). With more, the code reads a fixed simplex lattice from a file, which its loader cannot parse; here `number_of_weights` s-energy vectors are shrunk affinely onto the part of the simplex where every component is at least `epsilon`, which maps the simplex's corners to the corners of those files. Args: n_objectives (int): The number of objectives k. number_of_weights (int): The number of weight vectors N_mu. epsilon (float): The smallest component of `u`. Returns: np.ndarray: The weight vectors mu, one per row, in the order the fronts visit them. """ if n_objectives == 2: # noqa: PLR2004 first = epsilon + np.arange(number_of_weights) * (1 - 2 * epsilon) / (number_of_weights - 1) spread = np.column_stack([first, 1 - first]) else: lattice = create_s_energy(n_objectives, number_of_weights, seed=0) # should this seed also be connected to EA? spread = epsilon + (1 - n_objectives * epsilon) * lattice inverse = 1.0 / spread return inverse / inverse.sum(axis=1, keepdims=True) ``` #### moead_scalarize ``` moead_scalarize( targets: ndarray, weights: ndarray, ideal: ndarray, method: Literal["tchebycheff", "pbi", "weighted_sum"], pbi_penalty: float = 5.0, ) -> np.ndarray ``` Evaluate MOEA/D's aggregation functions, one weight vector per row of `targets`. All three are written for minimization, as in footnotes 3 and 6 of Zhang and Li (2007). - "tchebycheff": `max_k w_k |f_k - z_k|` (Eq. 3). - "pbi": `d1 + theta * d2` (Eq. 5), where `d1` is the length of the projection of `f - z` onto the weight vector and `d2` is the distance from `f` to the line through `z` along that vector. Eq. 5 writes the foot of the perpendicular as `z + d1 * w`, which is the projection only for a unit `w`. The weights here sum to one, so the geometric form shown in the paper's Fig. 2 is used, as PlatEMO and pymoo do. - "weighted_sum": `sum_k w_k f_k` (Eq. 2). The ideal point is not used. Parameters: | Name | Type | Description | Default | | ------------- | --------- | --------------------------------------------- | ---------- | | `targets` | `ndarray` | objective vectors (minimized), shape (n, m). | *required* | | `weights` | `ndarray` | the weight vector for each row, shape (n, m). | *required* | | `ideal` | `ndarray` | the reference point z, shape (m,). | *required* | | `method` | `str` | the aggregation function. | *required* | | `pbi_penalty` | `float` | the penalty theta of the PBI function. | `5.0` | Returns: | Type | Description | | --------- | --------------------------------------------------------------- | | `ndarray` | np.ndarray: the aggregation value of each row, lower is better. | Source code in `desdeo/emo/operators/selection.py` ``` def moead_scalarize( targets: np.ndarray, weights: np.ndarray, ideal: np.ndarray, method: Literal["tchebycheff", "pbi", "weighted_sum"], pbi_penalty: float = 5.0, ) -> np.ndarray: """Evaluate MOEA/D's aggregation functions, one weight vector per row of `targets`. All three are written for minimization, as in footnotes 3 and 6 of Zhang and Li (2007). - "tchebycheff": `max_k w_k |f_k - z_k|` (Eq. 3). - "pbi": `d1 + theta * d2` (Eq. 5), where `d1` is the length of the projection of `f - z` onto the weight vector and `d2` is the distance from `f` to the line through `z` along that vector. Eq. 5 writes the foot of the perpendicular as `z + d1 * w`, which is the projection only for a unit `w`. The weights here sum to one, so the geometric form shown in the paper's Fig. 2 is used, as PlatEMO and pymoo do. - "weighted_sum": `sum_k w_k f_k` (Eq. 2). The ideal point is not used. Args: targets (np.ndarray): objective vectors (minimized), shape `(n, m)`. weights (np.ndarray): the weight vector for each row, shape `(n, m)`. ideal (np.ndarray): the reference point `z`, shape `(m,)`. method (str): the aggregation function. pbi_penalty (float): the penalty `theta` of the PBI function. Returns: np.ndarray: the aggregation value of each row, lower is better. """ if method == "tchebycheff": return np.max(weights * np.abs(targets - ideal), axis=1) if method == "weighted_sum": return np.sum(weights * targets, axis=1) if method == "pbi": translated = targets - ideal norm = np.linalg.norm(weights, axis=1) norm[norm == 0] = np.finfo(float).eps unit = weights / norm[:, None] d1 = np.abs(np.sum(translated * unit, axis=1)) d2 = np.linalg.norm(translated - d1[:, None] * unit, axis=1) return d1 + pbi_penalty * d2 raise ValueError(f"Unknown MOEA/D aggregation function: {method}") ``` #### spea2_fitness ``` spea2_fitness( targets: ndarray, violations: ndarray | None = None ) -> tuple[np.ndarray, np.ndarray] ``` The SPEA2 fitness `F = R + D` of every solution, lower is better (Zitzler et al. 2001, Section 3.1). The strength `S(i)` counts the solutions `i` dominates and the raw fitness `R(i)` sums the strengths of the solutions dominating `i`, so `R = 0` exactly for the nondominated solutions. The density `D(i) = 1 / (sigma_i^k + 2)` uses the distance to the k-th nearest other solution in objective space, with `k = floor(sqrt(n))` for `n` solutions, and stays below one. Parameters: | Name | Type | Description | Default | | ------------ | --------- | ---------------------------------------------- | ---------------------------------------------------------------- | | `targets` | `ndarray` | the minimized objective vectors, shape (n, m). | *required* | | `violations` | \`ndarray | None\` | total constraint violations for constrained domination, or None. | Returns: | Type | Description | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `tuple[ndarray, ndarray]` | tuple\[np.ndarray, np.ndarray\]: the fitness F and the pairwise objective-space distances, whose diagonal is infinite. | Source code in `desdeo/emo/operators/selection.py` ``` def spea2_fitness(targets: np.ndarray, violations: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray]: """The SPEA2 fitness `F = R + D` of every solution, lower is better (Zitzler et al. 2001, Section 3.1). The strength `S(i)` counts the solutions `i` dominates and the raw fitness `R(i)` sums the strengths of the solutions dominating `i`, so `R = 0` exactly for the nondominated solutions. The density `D(i) = 1 / (sigma_i^k + 2)` uses the distance to the k-th nearest other solution in objective space, with `k = floor(sqrt(n))` for `n` solutions, and stays below one. Args: targets (np.ndarray): the minimized objective vectors, shape `(n, m)`. violations (np.ndarray | None): total constraint violations for constrained domination, or None. Returns: tuple[np.ndarray, np.ndarray]: the fitness `F` and the pairwise objective-space distances, whose diagonal is infinite. """ n = len(targets) dominance = constrained_dominance_matrix(targets, violations) strength = dominance.sum(axis=1) raw = (dominance * strength[:, None]).sum(axis=0) distances = cdist(targets, targets) np.fill_diagonal(distances, np.inf) if n < 2: # noqa: PLR2004 return raw.astype(float), distances k = min(int(np.sqrt(n)), n - 1) kth_nearest = np.sort(distances, axis=1)[:, k - 1] return raw + 1.0 / (kth_nearest + 2.0), distances ``` #### spea2_truncate ``` spea2_truncate(distances: ndarray, keep: int) -> list[int] ``` SPEA2's archive truncation: remove the most crowded solution until `keep` remain. At each step the solution whose sorted distances to the others still in the set are lexicographically smallest is removed: the one closest to another, ties broken by the second closest, and so on (Zitzler et al. 2001, Section 3.2). Boundary solutions are kept, since an extreme point always has a larger nearest-neighbour distance than its neighbour on the inside. Parameters: | Name | Type | Description | Default | | ----------- | --------- | ------------------------------------------------------------------- | ---------- | | `distances` | `ndarray` | pairwise distances among the candidates, with an infinite diagonal. | *required* | | `keep` | `int` | how many candidates to keep. | *required* | Returns: | Type | Description | | ----------- | -------------------------------------------------- | | `list[int]` | list\[int\]: the positions of the kept candidates. | Source code in `desdeo/emo/operators/selection.py` ``` def spea2_truncate(distances: np.ndarray, keep: int) -> list[int]: """SPEA2's archive truncation: remove the most crowded solution until `keep` remain. At each step the solution whose sorted distances to the others still in the set are lexicographically smallest is removed: the one closest to another, ties broken by the second closest, and so on (Zitzler et al. 2001, Section 3.2). Boundary solutions are kept, since an extreme point always has a larger nearest-neighbour distance than its neighbour on the inside. Args: distances (np.ndarray): pairwise distances among the candidates, with an infinite diagonal. keep (int): how many candidates to keep. Returns: list[int]: the positions of the kept candidates. """ return _spea2_truncate(distances, keep).tolist() ``` #### total_constraint_violation ``` total_constraint_violation( outputs: DataFrame, constraint_symbols: Sequence[str] | None, ) -> np.ndarray | None ``` Sum each solution's constraint violations, following DESDEO's positive-means-violated convention. Parameters: | Name | Type | Description | Default | | -------------------- | --------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------- | | `outputs` | `DataFrame` | The objective values, targets, and constraint values of a population. | *required* | | `constraint_symbols` | \`Sequence[str] | None\` | The constraint columns to read, or None for an unconstrained problem. | Returns: | Type | Description | | --------- | ----------- | | \`ndarray | None\` | Source code in `desdeo/emo/operators/selection.py` ``` def total_constraint_violation(outputs: pl.DataFrame, constraint_symbols: Sequence[str] | None) -> np.ndarray | None: """Sum each solution's constraint violations, following DESDEO's positive-means-violated convention. Args: outputs (pl.DataFrame): The objective values, targets, and constraint values of a population. constraint_symbols (Sequence[str] | None): The constraint columns to read, or None for an unconstrained problem. Returns: np.ndarray | None: A 1-D array of total violations, one per row, zero where feasible. None if the problem has no constraints, which lets callers keep the unconstrained code path. """ if not constraint_symbols: return None values = outputs[list(constraint_symbols)].to_numpy() return np.maximum(values, 0.0).sum(axis=1) ``` ## Scalar selection operators ### desdeo.emo.operators.scalar_selection Classs for scalar selection operators. #### BaseScalarSelector Bases: `Subscriber` A base class for selection operators. Source code in `desdeo/emo/operators/scalar_selection.py` ``` class BaseScalarSelector(Subscriber): """A base class for selection operators.""" @property def provided_topics(self): """The message topics provided by the selection operator.""" return { 0: [], 1: [], 2: [], } @property def interested_topics(self): """The message topics that the selection operator is interested in.""" return [ SelectorMessageTopics.SELECTED_FITNESS, ] def __init__(self, verbosity: int, publisher: Publisher): """Initialize a selection operator.""" super().__init__(verbosity=verbosity, publisher=publisher) self.fitness: np.ndarray | None = None @abstractmethod def _do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: solutions (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. fitness (np.ndarray | None, optional): The fitness values of the solutions. If None, the fitness is calculated from the messages sent by the publisher. Returns: SolutionType: The selected decision variables. """ def do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: solutions (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. fitness (np.ndarray | None, optional): The fitness values of the solutions. If None, the fitness is calculated from the messages sent by the publisher. Returns: SolutionType: The selected decision variables. """ if fitness is not None and self.fitness is not None: raise RuntimeError("The fitness is being set twice.") if fitness is None and self.fitness is None: raise RuntimeError( "The fitness is not set. Either pass it as an argument or make sure the publisher sends it." ) if fitness is None: fitness = self.fitness if len(fitness) != len(solutions[0]): raise ValueError( f"The length of the fitness array ({len(fitness)}) does not match" f" the number of solutions ({len(solutions[0])})." ) returnval = self._do(solutions, fitness) self.fitness = None # Reset fitness after selection return returnval def update(self, message: Message) -> None: """Update the operator with a message. Args: message (Message): The message to update the operator with. """ if message.topic == SelectorMessageTopics.SELECTED_FITNESS and isinstance(message.value, np.ndarray): self.fitness = message.value else: raise ValueError(f"Unknown message topic: {message.topic}") def state(self) -> Sequence[Message]: """Return the state of the selection operator.""" return [] ``` ##### interested_topics ``` interested_topics ``` The message topics that the selection operator is interested in. ##### provided_topics ``` provided_topics ``` The message topics provided by the selection operator. ##### __init__ ``` __init__(verbosity: int, publisher: Publisher) ``` Initialize a selection operator. Source code in `desdeo/emo/operators/scalar_selection.py` ``` def __init__(self, verbosity: int, publisher: Publisher): """Initialize a selection operator.""" super().__init__(verbosity=verbosity, publisher=publisher) self.fitness: np.ndarray | None = None ``` ##### \_do ``` _do( solutions: tuple[SolutionType, DataFrame], fitness: ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the selection operation. Parameters: | Name | Type | Description | Default | | ----------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `solutions` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | | `fitness` | \`ndarray | None\` | The fitness values of the solutions. If None, the fitness is calculated from the messages sent by the publisher. | Returns: | Name | Type | Description | | -------------- | -------------------------------- | -------------------------------- | | `SolutionType` | `tuple[SolutionType, DataFrame]` | The selected decision variables. | Source code in `desdeo/emo/operators/scalar_selection.py` ``` @abstractmethod def _do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: solutions (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. fitness (np.ndarray | None, optional): The fitness values of the solutions. If None, the fitness is calculated from the messages sent by the publisher. Returns: SolutionType: The selected decision variables. """ ``` ##### do ``` do( solutions: tuple[SolutionType, DataFrame], fitness: ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the selection operation. Parameters: | Name | Type | Description | Default | | ----------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `solutions` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | | `fitness` | \`ndarray | None\` | The fitness values of the solutions. If None, the fitness is calculated from the messages sent by the publisher. | Returns: | Name | Type | Description | | -------------- | -------------------------------- | -------------------------------- | | `SolutionType` | `tuple[SolutionType, DataFrame]` | The selected decision variables. | Source code in `desdeo/emo/operators/scalar_selection.py` ``` def do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """Perform the selection operation. Args: solutions (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. fitness (np.ndarray | None, optional): The fitness values of the solutions. If None, the fitness is calculated from the messages sent by the publisher. Returns: SolutionType: The selected decision variables. """ if fitness is not None and self.fitness is not None: raise RuntimeError("The fitness is being set twice.") if fitness is None and self.fitness is None: raise RuntimeError( "The fitness is not set. Either pass it as an argument or make sure the publisher sends it." ) if fitness is None: fitness = self.fitness if len(fitness) != len(solutions[0]): raise ValueError( f"The length of the fitness array ({len(fitness)}) does not match" f" the number of solutions ({len(solutions[0])})." ) returnval = self._do(solutions, fitness) self.fitness = None # Reset fitness after selection return returnval ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the selection operator. Source code in `desdeo/emo/operators/scalar_selection.py` ``` def state(self) -> Sequence[Message]: """Return the state of the selection operator.""" return [] ``` ##### update ``` update(message: Message) -> None ``` Update the operator with a message. Parameters: | Name | Type | Description | Default | | --------- | --------- | ---------------------------------------- | ---------- | | `message` | `Message` | The message to update the operator with. | *required* | Source code in `desdeo/emo/operators/scalar_selection.py` ``` def update(self, message: Message) -> None: """Update the operator with a message. Args: message (Message): The message to update the operator with. """ if message.topic == SelectorMessageTopics.SELECTED_FITNESS and isinstance(message.value, np.ndarray): self.fitness = message.value else: raise ValueError(f"Unknown message topic: {message.topic}") ``` #### ElitistSelection Bases: `BaseScalarSelector` Deterministic elitist selection: keep the top `winner_size` rows by a single output column. The selector ranks the combined `(decision_variables, outputs)` tuple by the values of `outputs[target_column]` (lower is better) and returns the best `winner_size` rows. No randomness, so the operation is reproducible. Useful as an elitist scheme for any single fitness column already present in the outputs DataFrame, e.g. an achievement scalarizing function value added via desdeo.tools.scalarization.add_asf_nondiff. Source code in `desdeo/emo/operators/scalar_selection.py` ``` class ElitistSelection(BaseScalarSelector): """Deterministic elitist selection: keep the top ``winner_size`` rows by a single output column. The selector ranks the combined ``(decision_variables, outputs)`` tuple by the values of ``outputs[target_column]`` (lower is better) and returns the best ``winner_size`` rows. No randomness, so the operation is reproducible. Useful as an elitist scheme for any single fitness column already present in the outputs DataFrame, e.g. an achievement scalarizing function value added via [desdeo.tools.scalarization.add_asf_nondiff][]. """ @property def provided_topics(self): """Topics published by this selector for each verbosity level.""" return { 0: [], 1: [SelectorMessageTopics.STATE], 2: [SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, SelectorMessageTopics.SELECTED_FITNESS], } @property def interested_topics(self): """ElitistSelection reads its fitness column from the outputs DataFrame; no subscriptions needed.""" return [] def __init__( self, *, winner_size: int, target_column: str, verbosity: int, publisher: Publisher, ): """Initialize the elitist scalar selector. Args: winner_size (int): The number of individuals to keep after selection. target_column (str): Name of the output column to sort by (ascending, lower is better). verbosity (int): Verbosity level for emitted messages. publisher (Publisher): Publisher used to emit selection state. """ super().__init__(verbosity=verbosity, publisher=publisher) self.winner_size = winner_size self.target_column = target_column self.selection: list[int] | None = None self.selected_individuals: SolutionType | None = None self.selected_targets: pl.DataFrame | None = None def do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """Keep the top ``winner_size`` rows by ``target_column`` (ascending). Args: solutions (tuple[SolutionType, pl.DataFrame]): Combined parents and offspring as a single ``(decision_variables, outputs)`` tuple. fitness (np.ndarray | None, optional): Optional fitness override. If ``None`` (the usual case), the values in ``outputs[target_column]`` are used. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their outputs. """ decvars, outputs = solutions values = fitness if fitness is not None else outputs[self.target_column].to_numpy() order = np.argsort(values, kind="stable") chosen = order[: self.winner_size].tolist() if isinstance(decvars, pl.DataFrame): self.selected_individuals = decvars[chosen] else: self.selected_individuals = [decvars[i] for i in chosen] self.selected_targets = outputs[chosen] self.selection = chosen self.fitness = np.asarray(values)[chosen] self.notify() return self.selected_individuals, self.selected_targets def _do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """ABC requirement: delegate to the public `do()`.""" return self.do(solutions, fitness) def state(self) -> Sequence[Message]: """Emit the selection state for archivers and other listeners.""" if self.verbosity == 0 or self.selection is None or self.selected_targets is None: return [] if self.verbosity == 1: return [ DictMessage( topic=SelectorMessageTopics.STATE, value={ "winner_size": self.winner_size, "selected_individuals": self.selection, }, source=self.__class__.__name__, ) ] # verbosity == 2 if isinstance(self.selected_individuals, pl.DataFrame): message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_targets, source=self.__class__.__name__, ) return [ DictMessage( topic=SelectorMessageTopics.STATE, value={ "winner_size": self.winner_size, "selected_individuals": self.selection, }, source=self.__class__.__name__, ), message, NumpyArrayMessage( topic=SelectorMessageTopics.SELECTED_FITNESS, value=self.fitness, source=self.__class__.__name__, ), ] def update(self, message: Message) -> None: """ElitistSelection has no subscriptions; ignore any messages.""" ``` ##### interested_topics ``` interested_topics ``` ElitistSelection reads its fitness column from the outputs DataFrame; no subscriptions needed. ##### provided_topics ``` provided_topics ``` Topics published by this selector for each verbosity level. ##### __init__ ``` __init__( *, winner_size: int, target_column: str, verbosity: int, publisher: Publisher, ) ``` Initialize the elitist scalar selector. Parameters: | Name | Type | Description | Default | | --------------- | ----------- | ------------------------------------------------------------------ | ---------- | | `winner_size` | `int` | The number of individuals to keep after selection. | *required* | | `target_column` | `str` | Name of the output column to sort by (ascending, lower is better). | *required* | | `verbosity` | `int` | Verbosity level for emitted messages. | *required* | | `publisher` | `Publisher` | Publisher used to emit selection state. | *required* | Source code in `desdeo/emo/operators/scalar_selection.py` ``` def __init__( self, *, winner_size: int, target_column: str, verbosity: int, publisher: Publisher, ): """Initialize the elitist scalar selector. Args: winner_size (int): The number of individuals to keep after selection. target_column (str): Name of the output column to sort by (ascending, lower is better). verbosity (int): Verbosity level for emitted messages. publisher (Publisher): Publisher used to emit selection state. """ super().__init__(verbosity=verbosity, publisher=publisher) self.winner_size = winner_size self.target_column = target_column self.selection: list[int] | None = None self.selected_individuals: SolutionType | None = None self.selected_targets: pl.DataFrame | None = None ``` ##### \_do ``` _do( solutions: tuple[SolutionType, DataFrame], fitness: ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame] ``` ABC requirement: delegate to the public `do()`. Source code in `desdeo/emo/operators/scalar_selection.py` ``` def _do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """ABC requirement: delegate to the public `do()`.""" return self.do(solutions, fitness) ``` ##### do ``` do( solutions: tuple[SolutionType, DataFrame], fitness: ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame] ``` Keep the top `winner_size` rows by `target_column` (ascending). Parameters: | Name | Type | Description | Default | | ----------- | -------------------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | `solutions` | `tuple[SolutionType, DataFrame]` | Combined parents and offspring as a single (decision_variables, outputs) tuple. | *required* | | `fitness` | \`ndarray | None\` | Optional fitness override. If None (the usual case), the values in outputs[target_column] are used. | Returns: | Type | Description | | -------------------------------- | --------------------------------------------------------------------------------------- | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: The selected decision variables and their outputs. | Source code in `desdeo/emo/operators/scalar_selection.py` ``` def do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """Keep the top ``winner_size`` rows by ``target_column`` (ascending). Args: solutions (tuple[SolutionType, pl.DataFrame]): Combined parents and offspring as a single ``(decision_variables, outputs)`` tuple. fitness (np.ndarray | None, optional): Optional fitness override. If ``None`` (the usual case), the values in ``outputs[target_column]`` are used. Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their outputs. """ decvars, outputs = solutions values = fitness if fitness is not None else outputs[self.target_column].to_numpy() order = np.argsort(values, kind="stable") chosen = order[: self.winner_size].tolist() if isinstance(decvars, pl.DataFrame): self.selected_individuals = decvars[chosen] else: self.selected_individuals = [decvars[i] for i in chosen] self.selected_targets = outputs[chosen] self.selection = chosen self.fitness = np.asarray(values)[chosen] self.notify() return self.selected_individuals, self.selected_targets ``` ##### state ``` state() -> Sequence[Message] ``` Emit the selection state for archivers and other listeners. Source code in `desdeo/emo/operators/scalar_selection.py` ``` def state(self) -> Sequence[Message]: """Emit the selection state for archivers and other listeners.""" if self.verbosity == 0 or self.selection is None or self.selected_targets is None: return [] if self.verbosity == 1: return [ DictMessage( topic=SelectorMessageTopics.STATE, value={ "winner_size": self.winner_size, "selected_individuals": self.selection, }, source=self.__class__.__name__, ) ] # verbosity == 2 if isinstance(self.selected_individuals, pl.DataFrame): message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_individuals.hstack(self.selected_targets), source=self.__class__.__name__, ) else: warnings.warn("Population is not a Polars DataFrame. Defaulting to providing OUTPUTS only.", stacklevel=2) message = PolarsDataFrameMessage( topic=SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, value=self.selected_targets, source=self.__class__.__name__, ) return [ DictMessage( topic=SelectorMessageTopics.STATE, value={ "winner_size": self.winner_size, "selected_individuals": self.selection, }, source=self.__class__.__name__, ), message, NumpyArrayMessage( topic=SelectorMessageTopics.SELECTED_FITNESS, value=self.fitness, source=self.__class__.__name__, ), ] ``` ##### update ``` update(message: Message) -> None ``` ElitistSelection has no subscriptions; ignore any messages. Source code in `desdeo/emo/operators/scalar_selection.py` ``` def update(self, message: Message) -> None: """ElitistSelection has no subscriptions; ignore any messages.""" ``` #### TournamentSelection Bases: `BaseScalarSelector` A tournament selection operator. The members of a tournament are compared either by the fitness the selector publishes or by (constrained) Pareto dominance on the targets. Source code in `desdeo/emo/operators/scalar_selection.py` ``` class TournamentSelection(BaseScalarSelector): """A tournament selection operator. The members of a tournament are compared either by the fitness the selector publishes or by (constrained) Pareto dominance on the targets. """ def __init__( self, *, winner_size: int, verbosity: int, publisher: Publisher, tournament_size: int = 2, seed: int = 0, stochastic: bool = False, selection_probability: float | None = None, comparison: Literal["fitness", "dominance"] = "fitness", target_symbols: Sequence[str] | None = None, constraint_symbols: Sequence[str] | None = None, ) -> None: """Initialize the tournament selection operator. Args: winner_size (int): The number of winners to select. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to send messages to. tournament_size (int, optional): The size of the tournament. Defaults to 2, which corresponds to binary tournament. seed (int, optional): The seed for the random number generator, which draws the tournaments and, when `stochastic` is set, the winner within each one. Defaults to 0. stochastic (bool, optional): If False, the solution with the highest fitness in the tournament always wins. If True, the winner is drawn at random, with a probability proportional to fitness unless `selection_probability` says otherwise, which is roulette wheel selection. Defaults to False. selection_probability (float | None, optional): The probability of selecting a solution in the tournament, only meaningful when `stochastic` is set. If None, the probabilities are proportional to the fitness values of the solutions in the tournament. If a value p is given, the probability of choosing the k-best solution in the tournament is p * (1 - p) ** (k - 1). comparison (Literal["fitness", "dominance"], optional): How the members of a tournament are compared. "fitness" uses the published fitness. "dominance" draws the winner uniformly from the members that no other member dominates, under constrained domination: a feasible solution beats an infeasible one, and of two infeasible solutions the one with the smaller total violation wins. The published fitness is then ignored. Defaults to "fitness". target_symbols (Sequence[str] | None, optional): The minimized target columns that dominance is computed on. Required when `comparison` is "dominance". constraint_symbols (Sequence[str] | None, optional): The constraint columns, positive when violated. None for an unconstrained problem. Only used when `comparison` is "dominance". Raises: ValueError: If `selection_probability` is given without `stochastic`, which would silently ignore it, if `comparison` is "dominance" without `target_symbols`, or if it is combined with `stochastic`. Note: `seed` used to double as the switch between the two rules, so that leaving it unset made the selection deterministic *and* seeded the generator from OS entropy. That made a whole run irreproducible even with a fixed template seed, so the two are now separate: `seed` only seeds, and `stochastic` only chooses the rule. The members of a tournament are drawn with replacement. jMetal's `BinaryTournament2`, which WASF-GA's reference code uses with a dominance comparator, draws pairs from a permutation instead. """ super().__init__(verbosity=verbosity, publisher=publisher) self.winner_size = winner_size self.tournament_size = tournament_size self.seed = seed self.rng = np.random.default_rng(seed) self.stochastic = stochastic self.selection_probability = selection_probability self.comparison = comparison self.target_symbols = list(target_symbols or []) self.constraint_symbols = list(constraint_symbols) if constraint_symbols else None if not self.stochastic and self.selection_probability is not None: raise ValueError("If selection_probability is provided, stochastic must be True for it to have an effect.") if self.comparison == "dominance": if not self.target_symbols: raise ValueError("A dominance tournament needs the target symbols to compare the members on.") if self.stochastic: raise ValueError("A dominance tournament has no fitness to draw a stochastic winner by.") def do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """Perform the tournament selection operation. Args: solutions (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. fitness (np.ndarray | None, optional): The fitness values of the solutions. If None, the fitness is taken from the messages sent by the publisher. Ignored when `comparison` is "dominance". Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their outputs. """ if self.comparison == "fitness": return super().do(solutions, fitness) # The selector may still publish a fitness; it plays no part here, but must not linger to the next call. self.fitness = None return self._do(solutions) def dominance_select(self, indices: np.ndarray, dominance: np.ndarray) -> int: """Select uniformly at random among the members of a tournament that no other member dominates. Args: indices (np.ndarray): The indices of the tournament's members. dominance (np.ndarray): The population's dominance matrix; `dominance[i, j]` is True when i dominates j. Returns: int: The index of the selected solution. """ within = dominance[np.ix_(indices, indices)] undominated = indices[~within.any(axis=0)] return self.rng.choice(undominated) @staticmethod def deterministic_select(indices: np.ndarray, fitness: np.ndarray) -> int: """Select the index of the solution with the highest fitness from the given indices. Args: indices (np.ndarray): The indices of the solutions to select from. fitness (np.ndarray): The fitness values of the solutions. Returns: int: The index of the solution with the highest fitness. """ return indices[np.argmax(fitness)] def stochastic_select(self, indices: np.ndarray, fitness: np.ndarray) -> int: """Select the index of the solution with a probability proportional to its fitness from the given indices. Args: indices (np.ndarray): The indices of the solutions to select from. fitness (np.ndarray): The fitness values of the solutions. Returns: int: The index of the selected solution. """ if self.selection_probability is None: # Fitness can sum to zero (e.g. all-zero fitness), giving 0/0; the resulting nan is acceptable. with np.errstate(divide="ignore", invalid="ignore"): probabilities = fitness / np.sum(fitness) probabilities = np.cumsum(probabilities) else: indices = indices[np.argsort(fitness)[::-1]] # Sort indices by fitness in descending order probabilities = np.array( [self.selection_probability * (1 - self.selection_probability) ** i for i in range(len(indices))] ) random_value = self.rng.random() selected_index = np.searchsorted(probabilities, random_value) return indices[selected_index] def _do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None ) -> tuple[SolutionType, pl.DataFrame]: """Perform the tournament selection operation. Args: solutions (tuple[SolutionType, pl.DataFrame]): The decision variables and their outputs. fitness (np.ndarray | None, optional): The fitness values of the solutions. Unused when `comparison` is "dominance". Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their outputs. """ dominance = None if self.comparison == "dominance": dominance = constrained_dominance_matrix( solutions[1][self.target_symbols].to_numpy(), total_constraint_violation(solutions[1], self.constraint_symbols), ) selected_indices = np.zeros(self.winner_size, dtype=int) for i in range(self.winner_size): tournament_indices = self.rng.choice(range(len(solutions[0])), size=self.tournament_size, replace=True) if dominance is not None: selected_indices[i] = self.dominance_select(tournament_indices, dominance) elif self.stochastic: selected_indices[i] = self.stochastic_select(tournament_indices, fitness[tournament_indices]) else: selected_indices[i] = self.deterministic_select(tournament_indices, fitness[tournament_indices]) selected_solutions = solutions[0][selected_indices] selected_outputs = solutions[1][selected_indices] return selected_solutions, selected_outputs ``` ##### __init__ ``` __init__( *, winner_size: int, verbosity: int, publisher: Publisher, tournament_size: int = 2, seed: int = 0, stochastic: bool = False, selection_probability: float | None = None, comparison: Literal["fitness", "dominance"] = "fitness", target_symbols: Sequence[str] | None = None, constraint_symbols: Sequence[str] | None = None, ) -> None ``` Initialize the tournament selection operator. Parameters: | Name | Type | Description | Default | | ----------------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `winner_size` | `int` | The number of winners to select. | *required* | | `verbosity` | `int` | The verbosity level of the operator. | *required* | | `publisher` | `Publisher` | The publisher to send messages to. | *required* | | `tournament_size` | `int` | The size of the tournament. Defaults to 2, which corresponds to binary tournament. | `2` | | `seed` | `int` | The seed for the random number generator, which draws the tournaments and, when stochastic is set, the winner within each one. Defaults to 0. | `0` | | `stochastic` | `bool` | If False, the solution with the highest fitness in the tournament always wins. If True, the winner is drawn at random, with a probability proportional to fitness unless selection_probability says otherwise, which is roulette wheel selection. Defaults to False. | `False` | | `selection_probability` | \`float | None\` | The probability of selecting a solution in the tournament, only meaningful when stochastic is set. If None, the probabilities are proportional to the fitness values of the solutions in the tournament. If a value p is given, the probability of choosing the k-best solution in the tournament is p * (1 - p) \*\* (k - 1). | | `comparison` | `Literal['fitness', 'dominance']` | How the members of a tournament are compared. "fitness" uses the published fitness. "dominance" draws the winner uniformly from the members that no other member dominates, under constrained domination: a feasible solution beats an infeasible one, and of two infeasible solutions the one with the smaller total violation wins. The published fitness is then ignored. Defaults to "fitness". | `'fitness'` | | `target_symbols` | \`Sequence[str] | None\` | The minimized target columns that dominance is computed on. Required when comparison is "dominance". | | `constraint_symbols` | \`Sequence[str] | None\` | The constraint columns, positive when violated. None for an unconstrained problem. Only used when comparison is "dominance". | Raises: | Type | Description | | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ValueError` | If selection_probability is given without stochastic, which would silently ignore it, if comparison is "dominance" without target_symbols, or if it is combined with stochastic. | Note `seed` used to double as the switch between the two rules, so that leaving it unset made the selection deterministic *and* seeded the generator from OS entropy. That made a whole run irreproducible even with a fixed template seed, so the two are now separate: `seed` only seeds, and `stochastic` only chooses the rule. The members of a tournament are drawn with replacement. jMetal's `BinaryTournament2`, which WASF-GA's reference code uses with a dominance comparator, draws pairs from a permutation instead. Source code in `desdeo/emo/operators/scalar_selection.py` ``` def __init__( self, *, winner_size: int, verbosity: int, publisher: Publisher, tournament_size: int = 2, seed: int = 0, stochastic: bool = False, selection_probability: float | None = None, comparison: Literal["fitness", "dominance"] = "fitness", target_symbols: Sequence[str] | None = None, constraint_symbols: Sequence[str] | None = None, ) -> None: """Initialize the tournament selection operator. Args: winner_size (int): The number of winners to select. verbosity (int): The verbosity level of the operator. publisher (Publisher): The publisher to send messages to. tournament_size (int, optional): The size of the tournament. Defaults to 2, which corresponds to binary tournament. seed (int, optional): The seed for the random number generator, which draws the tournaments and, when `stochastic` is set, the winner within each one. Defaults to 0. stochastic (bool, optional): If False, the solution with the highest fitness in the tournament always wins. If True, the winner is drawn at random, with a probability proportional to fitness unless `selection_probability` says otherwise, which is roulette wheel selection. Defaults to False. selection_probability (float | None, optional): The probability of selecting a solution in the tournament, only meaningful when `stochastic` is set. If None, the probabilities are proportional to the fitness values of the solutions in the tournament. If a value p is given, the probability of choosing the k-best solution in the tournament is p * (1 - p) ** (k - 1). comparison (Literal["fitness", "dominance"], optional): How the members of a tournament are compared. "fitness" uses the published fitness. "dominance" draws the winner uniformly from the members that no other member dominates, under constrained domination: a feasible solution beats an infeasible one, and of two infeasible solutions the one with the smaller total violation wins. The published fitness is then ignored. Defaults to "fitness". target_symbols (Sequence[str] | None, optional): The minimized target columns that dominance is computed on. Required when `comparison` is "dominance". constraint_symbols (Sequence[str] | None, optional): The constraint columns, positive when violated. None for an unconstrained problem. Only used when `comparison` is "dominance". Raises: ValueError: If `selection_probability` is given without `stochastic`, which would silently ignore it, if `comparison` is "dominance" without `target_symbols`, or if it is combined with `stochastic`. Note: `seed` used to double as the switch between the two rules, so that leaving it unset made the selection deterministic *and* seeded the generator from OS entropy. That made a whole run irreproducible even with a fixed template seed, so the two are now separate: `seed` only seeds, and `stochastic` only chooses the rule. The members of a tournament are drawn with replacement. jMetal's `BinaryTournament2`, which WASF-GA's reference code uses with a dominance comparator, draws pairs from a permutation instead. """ super().__init__(verbosity=verbosity, publisher=publisher) self.winner_size = winner_size self.tournament_size = tournament_size self.seed = seed self.rng = np.random.default_rng(seed) self.stochastic = stochastic self.selection_probability = selection_probability self.comparison = comparison self.target_symbols = list(target_symbols or []) self.constraint_symbols = list(constraint_symbols) if constraint_symbols else None if not self.stochastic and self.selection_probability is not None: raise ValueError("If selection_probability is provided, stochastic must be True for it to have an effect.") if self.comparison == "dominance": if not self.target_symbols: raise ValueError("A dominance tournament needs the target symbols to compare the members on.") if self.stochastic: raise ValueError("A dominance tournament has no fitness to draw a stochastic winner by.") ``` ##### \_do ``` _do( solutions: tuple[SolutionType, DataFrame], fitness: ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the tournament selection operation. Parameters: | Name | Type | Description | Default | | ----------- | -------------------------------- | ----------------------------------------- | --------------------------------------------------------------------------- | | `solutions` | `tuple[SolutionType, DataFrame]` | The decision variables and their outputs. | *required* | | `fitness` | \`ndarray | None\` | The fitness values of the solutions. Unused when comparison is "dominance". | Returns: | Type | Description | | -------------------------------- | --------------------------------------------------------------------------------------- | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: The selected decision variables and their outputs. | Source code in `desdeo/emo/operators/scalar_selection.py` ``` def _do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None ) -> tuple[SolutionType, pl.DataFrame]: """Perform the tournament selection operation. Args: solutions (tuple[SolutionType, pl.DataFrame]): The decision variables and their outputs. fitness (np.ndarray | None, optional): The fitness values of the solutions. Unused when `comparison` is "dominance". Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their outputs. """ dominance = None if self.comparison == "dominance": dominance = constrained_dominance_matrix( solutions[1][self.target_symbols].to_numpy(), total_constraint_violation(solutions[1], self.constraint_symbols), ) selected_indices = np.zeros(self.winner_size, dtype=int) for i in range(self.winner_size): tournament_indices = self.rng.choice(range(len(solutions[0])), size=self.tournament_size, replace=True) if dominance is not None: selected_indices[i] = self.dominance_select(tournament_indices, dominance) elif self.stochastic: selected_indices[i] = self.stochastic_select(tournament_indices, fitness[tournament_indices]) else: selected_indices[i] = self.deterministic_select(tournament_indices, fitness[tournament_indices]) selected_solutions = solutions[0][selected_indices] selected_outputs = solutions[1][selected_indices] return selected_solutions, selected_outputs ``` ##### deterministic_select ``` deterministic_select( indices: ndarray, fitness: ndarray ) -> int ``` Select the index of the solution with the highest fitness from the given indices. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------- | ---------- | | `indices` | `ndarray` | The indices of the solutions to select from. | *required* | | `fitness` | `ndarray` | The fitness values of the solutions. | *required* | Returns: | Name | Type | Description | | ----- | ----- | --------------------------------------------------- | | `int` | `int` | The index of the solution with the highest fitness. | Source code in `desdeo/emo/operators/scalar_selection.py` ``` @staticmethod def deterministic_select(indices: np.ndarray, fitness: np.ndarray) -> int: """Select the index of the solution with the highest fitness from the given indices. Args: indices (np.ndarray): The indices of the solutions to select from. fitness (np.ndarray): The fitness values of the solutions. Returns: int: The index of the solution with the highest fitness. """ return indices[np.argmax(fitness)] ``` ##### do ``` do( solutions: tuple[SolutionType, DataFrame], fitness: ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame] ``` Perform the tournament selection operation. Parameters: | Name | Type | Description | Default | | ----------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `solutions` | `tuple[SolutionType, DataFrame]` | the decision variables as the first element. The second element is the objective values, targets, and constraint violations. | *required* | | `fitness` | \`ndarray | None\` | The fitness values of the solutions. If None, the fitness is taken from the messages sent by the publisher. Ignored when comparison is "dominance". | Returns: | Type | Description | | -------------------------------- | --------------------------------------------------------------------------------------- | | `tuple[SolutionType, DataFrame]` | tuple\[SolutionType, pl.DataFrame\]: The selected decision variables and their outputs. | Source code in `desdeo/emo/operators/scalar_selection.py` ``` def do( self, solutions: tuple[SolutionType, pl.DataFrame], fitness: np.ndarray | None = None, ) -> tuple[SolutionType, pl.DataFrame]: """Perform the tournament selection operation. Args: solutions (tuple[SolutionType, pl.DataFrame]): the decision variables as the first element. The second element is the objective values, targets, and constraint violations. fitness (np.ndarray | None, optional): The fitness values of the solutions. If None, the fitness is taken from the messages sent by the publisher. Ignored when `comparison` is "dominance". Returns: tuple[SolutionType, pl.DataFrame]: The selected decision variables and their outputs. """ if self.comparison == "fitness": return super().do(solutions, fitness) # The selector may still publish a fitness; it plays no part here, but must not linger to the next call. self.fitness = None return self._do(solutions) ``` ##### dominance_select ``` dominance_select( indices: ndarray, dominance: ndarray ) -> int ``` Select uniformly at random among the members of a tournament that no other member dominates. Parameters: | Name | Type | Description | Default | | ----------- | --------- | ------------------------------------------------------------------------------ | ---------- | | `indices` | `ndarray` | The indices of the tournament's members. | *required* | | `dominance` | `ndarray` | The population's dominance matrix; dominance[i, j] is True when i dominates j. | *required* | Returns: | Name | Type | Description | | ----- | ----- | ----------------------------------- | | `int` | `int` | The index of the selected solution. | Source code in `desdeo/emo/operators/scalar_selection.py` ``` def dominance_select(self, indices: np.ndarray, dominance: np.ndarray) -> int: """Select uniformly at random among the members of a tournament that no other member dominates. Args: indices (np.ndarray): The indices of the tournament's members. dominance (np.ndarray): The population's dominance matrix; `dominance[i, j]` is True when i dominates j. Returns: int: The index of the selected solution. """ within = dominance[np.ix_(indices, indices)] undominated = indices[~within.any(axis=0)] return self.rng.choice(undominated) ``` ##### stochastic_select ``` stochastic_select( indices: ndarray, fitness: ndarray ) -> int ``` Select the index of the solution with a probability proportional to its fitness from the given indices. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------- | ---------- | | `indices` | `ndarray` | The indices of the solutions to select from. | *required* | | `fitness` | `ndarray` | The fitness values of the solutions. | *required* | Returns: | Name | Type | Description | | ----- | ----- | ----------------------------------- | | `int` | `int` | The index of the selected solution. | Source code in `desdeo/emo/operators/scalar_selection.py` ``` def stochastic_select(self, indices: np.ndarray, fitness: np.ndarray) -> int: """Select the index of the solution with a probability proportional to its fitness from the given indices. Args: indices (np.ndarray): The indices of the solutions to select from. fitness (np.ndarray): The fitness values of the solutions. Returns: int: The index of the selected solution. """ if self.selection_probability is None: # Fitness can sum to zero (e.g. all-zero fitness), giving 0/0; the resulting nan is acceptable. with np.errstate(divide="ignore", invalid="ignore"): probabilities = fitness / np.sum(fitness) probabilities = np.cumsum(probabilities) else: indices = indices[np.argsort(fitness)[::-1]] # Sort indices by fitness in descending order probabilities = np.array( [self.selection_probability * (1 - self.selection_probability) ** i for i in range(len(indices))] ) random_value = self.rng.random() selected_index = np.searchsorted(probabilities, random_value) return indices[selected_index] ``` ## Termination criteria ### desdeo.emo.operators.termination The base class for termination criteria. The termination criterion is used to determine when the optimization process should stop. In this implementation, it also includes a simple counter for the number of elapsed generations. This counter is increased by one each time the termination criterion is called. The simplest termination criterion is reaching the maximum number of generations. The implementation also contains a counter for the number of evaluations. This counter is updated by the Evaluator and Generator classes. The termination criterion can be based on the number of evaluations as well. Warning Each subclass of BaseTerminator must implement the do method. The do method should always call the super().do method to increment the generation counter *before* conducting the termination check. #### BaseTerminator Bases: `Subscriber` The base class for the termination criteria. Also includes a simple counter for number of elapsed generations. This counter is increased by one each time the termination criterion is called. Source code in `desdeo/emo/operators/termination.py` ``` class BaseTerminator(Subscriber): """The base class for the termination criteria. Also includes a simple counter for number of elapsed generations. This counter is increased by one each time the termination criterion is called. """ @property def provided_topics(self) -> dict[int, Sequence[TerminatorMessageTopics]]: """Return the topics provided by the terminator. Returns: dict[int, Sequence[TerminatorMessageTopics]]: The topics provided by the terminator. """ return { 0: [], 1: [ TerminatorMessageTopics.GENERATION, TerminatorMessageTopics.EVALUATION, TerminatorMessageTopics.MAX_GENERATIONS, TerminatorMessageTopics.MAX_EVALUATIONS, ], } @property def interested_topics(self): """Return the message topics that the terminator is interested in.""" return [EvaluatorMessageTopics.NEW_EVALUATIONS] def __init__(self, publisher: Publisher): """Initialize a termination criterion.""" super().__init__(publisher=publisher, verbosity=1) self.current_generation: int = 1 self.current_evaluations: int = 0 self.max_generations: int = 0 self.max_evaluations: int = 0 def check(self) -> bool: """Check if the termination criterion is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ self.current_generation += 1 self.notify() def state(self) -> Sequence[Message]: """Return the state of the termination criterion.""" state = [ IntMessage( topic=TerminatorMessageTopics.GENERATION, value=self.current_generation, source=self.__class__.__name__, ), IntMessage( topic=TerminatorMessageTopics.EVALUATION, value=self.current_evaluations, source=self.__class__.__name__ ), ] if self.max_evaluations != 0: state.append( IntMessage( topic=TerminatorMessageTopics.MAX_EVALUATIONS, value=self.max_evaluations, source=self.__class__.__name__, ) ) if self.max_generations != 0: state.append( IntMessage( topic=TerminatorMessageTopics.MAX_GENERATIONS, value=self.max_generations, source=self.__class__.__name__, ) ) return state def update(self, message: Message) -> None: """Update the number of evaluations. Note that for this method to work, this class must be registered as an observer of a subject that sends messages with the key "num_evaluations". The Evaluator class does this. Args: message (dict): the message from the subject, must contain the key "num_evaluations". """ if not isinstance(message, IntMessage): return if not (isinstance(message.topic, (EvaluatorMessageTopics, GeneratorMessageTopics))): return if ( message.topic == EvaluatorMessageTopics.NEW_EVALUATIONS # NOQA: PLR1714 or message.topic == GeneratorMessageTopics.NEW_EVALUATIONS ): self.current_evaluations += message.value ``` ##### interested_topics ``` interested_topics ``` Return the message topics that the terminator is interested in. ##### provided_topics ``` provided_topics: dict[ int, Sequence[TerminatorMessageTopics] ] ``` Return the topics provided by the terminator. Returns: | Type | Description | | ---------------------------------------------- | -------------------------------------------------------------------------------------- | | `dict[int, Sequence[TerminatorMessageTopics]]` | dict\[int, Sequence[TerminatorMessageTopics]\]: The topics provided by the terminator. | ##### __init__ ``` __init__(publisher: Publisher) ``` Initialize a termination criterion. Source code in `desdeo/emo/operators/termination.py` ``` def __init__(self, publisher: Publisher): """Initialize a termination criterion.""" super().__init__(publisher=publisher, verbosity=1) self.current_generation: int = 1 self.current_evaluations: int = 0 self.max_generations: int = 0 self.max_evaluations: int = 0 ``` ##### check ``` check() -> bool ``` Check if the termination criterion is reached. Returns: | Name | Type | Description | | ------ | ------ | -------------------------------------------------------------- | | `bool` | `bool` | True if the termination criterion is reached, False otherwise. | Source code in `desdeo/emo/operators/termination.py` ``` def check(self) -> bool: """Check if the termination criterion is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ self.current_generation += 1 self.notify() ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the termination criterion. Source code in `desdeo/emo/operators/termination.py` ``` def state(self) -> Sequence[Message]: """Return the state of the termination criterion.""" state = [ IntMessage( topic=TerminatorMessageTopics.GENERATION, value=self.current_generation, source=self.__class__.__name__, ), IntMessage( topic=TerminatorMessageTopics.EVALUATION, value=self.current_evaluations, source=self.__class__.__name__ ), ] if self.max_evaluations != 0: state.append( IntMessage( topic=TerminatorMessageTopics.MAX_EVALUATIONS, value=self.max_evaluations, source=self.__class__.__name__, ) ) if self.max_generations != 0: state.append( IntMessage( topic=TerminatorMessageTopics.MAX_GENERATIONS, value=self.max_generations, source=self.__class__.__name__, ) ) return state ``` ##### update ``` update(message: Message) -> None ``` Update the number of evaluations. Note that for this method to work, this class must be registered as an observer of a subject that sends messages with the key "num_evaluations". The Evaluator class does this. Parameters: | Name | Type | Description | Default | | --------- | ------ | --------------------------------------------------------------------- | ---------- | | `message` | `dict` | the message from the subject, must contain the key "num_evaluations". | *required* | Source code in `desdeo/emo/operators/termination.py` ``` def update(self, message: Message) -> None: """Update the number of evaluations. Note that for this method to work, this class must be registered as an observer of a subject that sends messages with the key "num_evaluations". The Evaluator class does this. Args: message (dict): the message from the subject, must contain the key "num_evaluations". """ if not isinstance(message, IntMessage): return if not (isinstance(message.topic, (EvaluatorMessageTopics, GeneratorMessageTopics))): return if ( message.topic == EvaluatorMessageTopics.NEW_EVALUATIONS # NOQA: PLR1714 or message.topic == GeneratorMessageTopics.NEW_EVALUATIONS ): self.current_evaluations += message.value ``` #### CompositeTerminator Bases: `BaseTerminator` Combines multiple terminators using logical AND or OR. Source code in `desdeo/emo/operators/termination.py` ``` class CompositeTerminator(BaseTerminator): """Combines multiple terminators using logical AND or OR.""" def __init__(self, terminators: list[BaseTerminator], publisher: Publisher, mode: str = "any"): """Initialize a composite termination criterion. Args: terminators (list[BaseTerminator]): List of BaseTerminator instances. publisher (Publisher): Publisher for passing messages. mode (str): "any" (terminate if any) or "all" (terminate if all). By default, "any". """ super().__init__(publisher=publisher) self.terminators = terminators for t in self.terminators: t.notify = lambda: None # Reset the notify method so that individual terminators do not send notifications types = [type(t) for t in self.terminators] # Assert that all terminators are unique if len(types) != len(set(types)): raise ValueError("All terminators must be unique.") max_generations = [t.max_generations for t in self.terminators if isinstance(t, MaxGenerationsTerminator)] if max_generations: self.max_generations = max(max_generations) max_evaluations = [t.max_evaluations for t in self.terminators if isinstance(t, MaxEvaluationsTerminator)] if max_evaluations: self.max_evaluations = max(max_evaluations) self.mode = mode def check(self) -> bool: """Check if the termination criterion is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ super().check() results = [t.check() for t in self.terminators] if self.mode == "all": return all(results) return any(results) ``` ##### __init__ ``` __init__( terminators: list[BaseTerminator], publisher: Publisher, mode: str = "any", ) ``` Initialize a composite termination criterion. Parameters: | Name | Type | Description | Default | | ------------- | ---------------------- | ------------------------------------------------------------------------ | ---------- | | `terminators` | `list[BaseTerminator]` | List of BaseTerminator instances. | *required* | | `publisher` | `Publisher` | Publisher for passing messages. | *required* | | `mode` | `str` | "any" (terminate if any) or "all" (terminate if all). By default, "any". | `'any'` | Source code in `desdeo/emo/operators/termination.py` ``` def __init__(self, terminators: list[BaseTerminator], publisher: Publisher, mode: str = "any"): """Initialize a composite termination criterion. Args: terminators (list[BaseTerminator]): List of BaseTerminator instances. publisher (Publisher): Publisher for passing messages. mode (str): "any" (terminate if any) or "all" (terminate if all). By default, "any". """ super().__init__(publisher=publisher) self.terminators = terminators for t in self.terminators: t.notify = lambda: None # Reset the notify method so that individual terminators do not send notifications types = [type(t) for t in self.terminators] # Assert that all terminators are unique if len(types) != len(set(types)): raise ValueError("All terminators must be unique.") max_generations = [t.max_generations for t in self.terminators if isinstance(t, MaxGenerationsTerminator)] if max_generations: self.max_generations = max(max_generations) max_evaluations = [t.max_evaluations for t in self.terminators if isinstance(t, MaxEvaluationsTerminator)] if max_evaluations: self.max_evaluations = max(max_evaluations) self.mode = mode ``` ##### check ``` check() -> bool ``` Check if the termination criterion is reached. Returns: | Name | Type | Description | | ------ | ------ | -------------------------------------------------------------- | | `bool` | `bool` | True if the termination criterion is reached, False otherwise. | Source code in `desdeo/emo/operators/termination.py` ``` def check(self) -> bool: """Check if the termination criterion is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ super().check() results = [t.check() for t in self.terminators] if self.mode == "all": return all(results) return any(results) ``` #### ExternalCheckTerminator Bases: `BaseTerminator` A termination criterion that checks an external condition. Source code in `desdeo/emo/operators/termination.py` ``` class ExternalCheckTerminator(BaseTerminator): """A termination criterion that checks an external condition.""" def __init__(self, check_function, publisher: Publisher): """Initialize the external check terminator. Args: check_function (callable): A function that returns True if the termination condition is met. publisher (Publisher): The publisher to send messages to. """ super().__init__(publisher=publisher) self.check_function = check_function def check(self) -> bool: """Check if the termination condition is met. Returns: bool: True if the termination condition is met, False otherwise. """ super().check() self.notify() return self.check_function() ``` ##### __init__ ``` __init__(check_function, publisher: Publisher) ``` Initialize the external check terminator. Parameters: | Name | Type | Description | Default | | ---------------- | ----------- | ----------------------------------------------------------------- | ---------- | | `check_function` | `callable` | A function that returns True if the termination condition is met. | *required* | | `publisher` | `Publisher` | The publisher to send messages to. | *required* | Source code in `desdeo/emo/operators/termination.py` ``` def __init__(self, check_function, publisher: Publisher): """Initialize the external check terminator. Args: check_function (callable): A function that returns True if the termination condition is met. publisher (Publisher): The publisher to send messages to. """ super().__init__(publisher=publisher) self.check_function = check_function ``` ##### check ``` check() -> bool ``` Check if the termination condition is met. Returns: | Name | Type | Description | | ------ | ------ | ---------------------------------------------------------- | | `bool` | `bool` | True if the termination condition is met, False otherwise. | Source code in `desdeo/emo/operators/termination.py` ``` def check(self) -> bool: """Check if the termination condition is met. Returns: bool: True if the termination condition is met, False otherwise. """ super().check() self.notify() return self.check_function() ``` #### MaxEvaluationsTerminator Bases: `BaseTerminator` A class for a termination criterion based on the number of evaluations. Source code in `desdeo/emo/operators/termination.py` ``` class MaxEvaluationsTerminator(BaseTerminator): """A class for a termination criterion based on the number of evaluations.""" def __init__(self, max_evaluations: int, publisher: Publisher): """Initialize a termination criterion based on the number of evaluations. Looks for messages with key "num_evaluations" to update the number of evaluations. Args: max_evaluations (int): the maximum number of evaluations. publisher (Publisher): The publisher to which the terminator will publish its state. publisher must be passed. See the Subscriber class for more information. """ super().__init__(publisher=publisher) if not isinstance(max_evaluations, int) or max_evaluations < 0: raise ValueError("max_evaluations must be a non-negative integer") self.max_evaluations = max_evaluations self.current_evaluations = 0 def check(self) -> bool: """Check if the termination criterion based on the number of generations is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ super().check() self.notify() return self.current_evaluations >= self.max_evaluations ``` ##### __init__ ``` __init__(max_evaluations: int, publisher: Publisher) ``` Initialize a termination criterion based on the number of evaluations. Looks for messages with key "num_evaluations" to update the number of evaluations. Parameters: | Name | Type | Description | Default | | ----------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `max_evaluations` | `int` | the maximum number of evaluations. | *required* | | `publisher` | `Publisher` | The publisher to which the terminator will publish its state. publisher must be passed. See the Subscriber class for more information. | *required* | Source code in `desdeo/emo/operators/termination.py` ``` def __init__(self, max_evaluations: int, publisher: Publisher): """Initialize a termination criterion based on the number of evaluations. Looks for messages with key "num_evaluations" to update the number of evaluations. Args: max_evaluations (int): the maximum number of evaluations. publisher (Publisher): The publisher to which the terminator will publish its state. publisher must be passed. See the Subscriber class for more information. """ super().__init__(publisher=publisher) if not isinstance(max_evaluations, int) or max_evaluations < 0: raise ValueError("max_evaluations must be a non-negative integer") self.max_evaluations = max_evaluations self.current_evaluations = 0 ``` ##### check ``` check() -> bool ``` Check if the termination criterion based on the number of generations is reached. Returns: | Name | Type | Description | | ------ | ------ | -------------------------------------------------------------- | | `bool` | `bool` | True if the termination criterion is reached, False otherwise. | Source code in `desdeo/emo/operators/termination.py` ``` def check(self) -> bool: """Check if the termination criterion based on the number of generations is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ super().check() self.notify() return self.current_evaluations >= self.max_evaluations ``` #### MaxGenerationsTerminator Bases: `BaseTerminator` A class for a termination criterion based on the number of generations. Source code in `desdeo/emo/operators/termination.py` ``` class MaxGenerationsTerminator(BaseTerminator): """A class for a termination criterion based on the number of generations.""" def __init__(self, max_generations: int, publisher: Publisher): """Initialize a termination criterion based on the number of generations. Args: max_generations (int): the maximum number of generations. publisher (Publisher): The publisher to which the terminator will publish its state. """ super().__init__(publisher=publisher) self.max_generations = max_generations def check(self) -> bool: """Check if the termination criterion based on the number of generations is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ super().check() self.notify() return self.current_generation > self.max_generations ``` ##### __init__ ``` __init__(max_generations: int, publisher: Publisher) ``` Initialize a termination criterion based on the number of generations. Parameters: | Name | Type | Description | Default | | ----------------- | ----------- | ------------------------------------------------------------- | ---------- | | `max_generations` | `int` | the maximum number of generations. | *required* | | `publisher` | `Publisher` | The publisher to which the terminator will publish its state. | *required* | Source code in `desdeo/emo/operators/termination.py` ``` def __init__(self, max_generations: int, publisher: Publisher): """Initialize a termination criterion based on the number of generations. Args: max_generations (int): the maximum number of generations. publisher (Publisher): The publisher to which the terminator will publish its state. """ super().__init__(publisher=publisher) self.max_generations = max_generations ``` ##### check ``` check() -> bool ``` Check if the termination criterion based on the number of generations is reached. Returns: | Name | Type | Description | | ------ | ------ | -------------------------------------------------------------- | | `bool` | `bool` | True if the termination criterion is reached, False otherwise. | Source code in `desdeo/emo/operators/termination.py` ``` def check(self) -> bool: """Check if the termination criterion based on the number of generations is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ super().check() self.notify() return self.current_generation > self.max_generations ``` #### MaxTimeTerminator Bases: `BaseTerminator` A termination criterion based on the maximum elapsed time. Source code in `desdeo/emo/operators/termination.py` ``` class MaxTimeTerminator(BaseTerminator): """A termination criterion based on the maximum elapsed time.""" @property def provided_topics(self) -> dict[int, Sequence[TerminatorMessageTopics]]: """Return the topics provided by the terminator. Returns: dict[int, Sequence[TerminatorMessageTopics]]: The topics provided by the terminator. """ return { 0: [], 1: [ TerminatorMessageTopics.GENERATION, TerminatorMessageTopics.EVALUATION, ], } def __init__(self, max_time_in_seconds: float, publisher: Publisher): """Initialize the maximum time terminator. Args: max_time_in_seconds (float): The maximum elapsed time in seconds. publisher (Publisher): The publisher to which the terminator will publish its state. """ super().__init__(publisher=publisher) if not isinstance(max_time_in_seconds, float) or max_time_in_seconds < 0: raise ValueError("max_time must be a non-negative float") self.max_time = max_time_in_seconds self.start_time = None def check(self) -> bool: """Check if the termination criterion based on the maximum elapsed time is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ super().check() self.notify() if self.start_time is None: self.start_time = time.perf_counter() elapsed_time = time.perf_counter() - self.start_time return elapsed_time >= self.max_time ``` ##### provided_topics ``` provided_topics: dict[ int, Sequence[TerminatorMessageTopics] ] ``` Return the topics provided by the terminator. Returns: | Type | Description | | ---------------------------------------------- | -------------------------------------------------------------------------------------- | | `dict[int, Sequence[TerminatorMessageTopics]]` | dict\[int, Sequence[TerminatorMessageTopics]\]: The topics provided by the terminator. | ##### __init__ ``` __init__(max_time_in_seconds: float, publisher: Publisher) ``` Initialize the maximum time terminator. Parameters: | Name | Type | Description | Default | | --------------------- | ----------- | ------------------------------------------------------------- | ---------- | | `max_time_in_seconds` | `float` | The maximum elapsed time in seconds. | *required* | | `publisher` | `Publisher` | The publisher to which the terminator will publish its state. | *required* | Source code in `desdeo/emo/operators/termination.py` ``` def __init__(self, max_time_in_seconds: float, publisher: Publisher): """Initialize the maximum time terminator. Args: max_time_in_seconds (float): The maximum elapsed time in seconds. publisher (Publisher): The publisher to which the terminator will publish its state. """ super().__init__(publisher=publisher) if not isinstance(max_time_in_seconds, float) or max_time_in_seconds < 0: raise ValueError("max_time must be a non-negative float") self.max_time = max_time_in_seconds self.start_time = None ``` ##### check ``` check() -> bool ``` Check if the termination criterion based on the maximum elapsed time is reached. Returns: | Name | Type | Description | | ------ | ------ | -------------------------------------------------------------- | | `bool` | `bool` | True if the termination criterion is reached, False otherwise. | Source code in `desdeo/emo/operators/termination.py` ``` def check(self) -> bool: """Check if the termination criterion based on the maximum elapsed time is reached. Returns: bool: True if the termination criterion is reached, False otherwise. """ super().check() self.notify() if self.start_time is None: self.start_time = time.perf_counter() elapsed_time = time.perf_counter() - self.start_time return elapsed_time >= self.max_time ``` ## Archivers ### desdeo.emo.hooks.archivers A collection of archivers for storing solutions evaluated during evolution. #### Archive Bases: `BaseArchive` An archiver that stores the solutions evaluated during evolution. Source code in `desdeo/emo/hooks/archivers.py` ``` class Archive(BaseArchive): """An archiver that stores the solutions evaluated during evolution.""" def update(self, message: Message) -> None: """Update the archiver with the new data. Args: message (Message): Message from the publisher. """ if ( message.topic == TerminatorMessageTopics.GENERATION # NOQA: PLR1714 or message.topic == SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS ): super().update(message) return data = message.value data = data.with_columns(generation=self.generation_number) if self.solutions is None: self.solutions = data else: self.solutions = pl.concat([self.solutions, data]) ``` ##### update ``` update(message: Message) -> None ``` Update the archiver with the new data. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------- | ---------- | | `message` | `Message` | Message from the publisher. | *required* | Source code in `desdeo/emo/hooks/archivers.py` ``` def update(self, message: Message) -> None: """Update the archiver with the new data. Args: message (Message): Message from the publisher. """ if ( message.topic == TerminatorMessageTopics.GENERATION # NOQA: PLR1714 or message.topic == SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS ): super().update(message) return data = message.value data = data.with_columns(generation=self.generation_number) if self.solutions is None: self.solutions = data else: self.solutions = pl.concat([self.solutions, data]) ``` #### BaseArchive Bases: `Subscriber` Base class for archivers. Source code in `desdeo/emo/hooks/archivers.py` ``` class BaseArchive(Subscriber): """Base class for archivers.""" @property def interested_topics(self) -> Sequence[MessageTopics]: """Return the message topics that the archiver is interested in.""" return [ GeneratorMessageTopics.VERBOSE_OUTPUTS, EvaluatorMessageTopics.VERBOSE_OUTPUTS, SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS, TerminatorMessageTopics.GENERATION, ] @property def provided_topics(self) -> dict[int, Sequence[MessageTopics]]: """Return the topics provided by the archiver.""" return {0: []} def __init__(self, *, problem: Problem, publisher: Publisher): """Initialize the base archiver. Args: problem (Problem): The problem being solved. publisher (Publisher): The publisher object. """ super().__init__(publisher, verbosity=0) self.solutions: pl.DataFrame = None self.selections: pl.DataFrame = None self.problem = problem self.generation_number = 1 def state(self) -> Sequence[Message]: """Return the state of the archiver.""" return [] def update(self, message: Message) -> None: """Updae the archiver with new data. Takes care of common archiving jobs. Make sure to run this for every archiver. Args: message (Message): Message from the publisher. """ if message.topic == TerminatorMessageTopics.GENERATION: self.generation_number = message.value return if message.topic == SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS: data: pl.DataFrame = message.value data = data.with_columns(generation=self.generation_number) if self.selections is None: self.selections = data else: self.selections = pl.concat([self.selections, data], how="vertical") return @property def results(self) -> EMOResult: """Return the results of the archiver.""" dec_vars = [x.symbol for x in self.problem.get_flattened_variables()] all_cols = self.solutions.columns non_decs = [col for col in all_cols if col not in dec_vars] return EMOResult(optimal_variables=self.solutions[dec_vars], optimal_outputs=self.solutions[non_decs]) ``` ##### interested_topics ``` interested_topics: Sequence[MessageTopics] ``` Return the message topics that the archiver is interested in. ##### provided_topics ``` provided_topics: dict[int, Sequence[MessageTopics]] ``` Return the topics provided by the archiver. ##### results ``` results: EMOResult ``` Return the results of the archiver. ##### __init__ ``` __init__(*, problem: Problem, publisher: Publisher) ``` Initialize the base archiver. Parameters: | Name | Type | Description | Default | | ----------- | ----------- | ------------------------- | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | | `publisher` | `Publisher` | The publisher object. | *required* | Source code in `desdeo/emo/hooks/archivers.py` ``` def __init__(self, *, problem: Problem, publisher: Publisher): """Initialize the base archiver. Args: problem (Problem): The problem being solved. publisher (Publisher): The publisher object. """ super().__init__(publisher, verbosity=0) self.solutions: pl.DataFrame = None self.selections: pl.DataFrame = None self.problem = problem self.generation_number = 1 ``` ##### state ``` state() -> Sequence[Message] ``` Return the state of the archiver. Source code in `desdeo/emo/hooks/archivers.py` ``` def state(self) -> Sequence[Message]: """Return the state of the archiver.""" return [] ``` ##### update ``` update(message: Message) -> None ``` Updae the archiver with new data. Takes care of common archiving jobs. Make sure to run this for every archiver. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------- | ---------- | | `message` | `Message` | Message from the publisher. | *required* | Source code in `desdeo/emo/hooks/archivers.py` ``` def update(self, message: Message) -> None: """Updae the archiver with new data. Takes care of common archiving jobs. Make sure to run this for every archiver. Args: message (Message): Message from the publisher. """ if message.topic == TerminatorMessageTopics.GENERATION: self.generation_number = message.value return if message.topic == SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS: data: pl.DataFrame = message.value data = data.with_columns(generation=self.generation_number) if self.selections is None: self.selections = data else: self.selections = pl.concat([self.selections, data], how="vertical") return ``` #### FeasibleArchive Bases: `BaseArchive` An archiver that stores all feasible solutions evaluated during evolution. Source code in `desdeo/emo/hooks/archivers.py` ``` class FeasibleArchive(BaseArchive): """An archiver that stores all feasible solutions evaluated during evolution.""" def __init__(self, *, problem: Problem, publisher: Publisher): """Initialize the archiver. Args: problem (Problem): The problem being solved. publisher (Publisher): The publisher object. """ super().__init__(problem=problem, publisher=publisher) if problem.constraints is None: raise ValueError("The problem has no constraints.") self.cons_symb = [x.symbol for x in problem.constraints] def update(self, message: Message) -> None: """Update the archiver with the new data. Args: message (Message): Message from the publisher. """ if ( message.topic == TerminatorMessageTopics.GENERATION # NOQA: PLR1714 or message.topic == SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS ): super().update(message) return data = message.value feasible_mask = (data[self.cons_symb] <= 0).to_numpy().all(axis=1) feasible_data = data.filter(feasible_mask) feasible_data = feasible_data.with_columns(generation=self.generation_number) if self.solutions is None: self.solutions = feasible_data else: self.solutions = pl.concat([self.solutions, feasible_data]) ``` ##### __init__ ``` __init__(*, problem: Problem, publisher: Publisher) ``` Initialize the archiver. Parameters: | Name | Type | Description | Default | | ----------- | ----------- | ------------------------- | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | | `publisher` | `Publisher` | The publisher object. | *required* | Source code in `desdeo/emo/hooks/archivers.py` ``` def __init__(self, *, problem: Problem, publisher: Publisher): """Initialize the archiver. Args: problem (Problem): The problem being solved. publisher (Publisher): The publisher object. """ super().__init__(problem=problem, publisher=publisher) if problem.constraints is None: raise ValueError("The problem has no constraints.") self.cons_symb = [x.symbol for x in problem.constraints] ``` ##### update ``` update(message: Message) -> None ``` Update the archiver with the new data. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------- | ---------- | | `message` | `Message` | Message from the publisher. | *required* | Source code in `desdeo/emo/hooks/archivers.py` ``` def update(self, message: Message) -> None: """Update the archiver with the new data. Args: message (Message): Message from the publisher. """ if ( message.topic == TerminatorMessageTopics.GENERATION # NOQA: PLR1714 or message.topic == SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS ): super().update(message) return data = message.value feasible_mask = (data[self.cons_symb] <= 0).to_numpy().all(axis=1) feasible_data = data.filter(feasible_mask) feasible_data = feasible_data.with_columns(generation=self.generation_number) if self.solutions is None: self.solutions = feasible_data else: self.solutions = pl.concat([self.solutions, feasible_data]) ``` #### NonDominatedArchive Bases: `Archive` An archiver that stores only the feasible non-dominated solutions evaluated during evolution. Source code in `desdeo/emo/hooks/archivers.py` ``` class NonDominatedArchive(Archive): """An archiver that stores only the feasible non-dominated solutions evaluated during evolution.""" def __init__(self, *, problem: Problem, publisher: Publisher): """Initialize the archiver. Args: problem (Problem): The problem being solved. publisher (Publisher): The publisher object. """ super().__init__(problem=problem, publisher=publisher) self.targets = [f"{x.symbol}_min" for x in problem.objectives] if problem.constraints is None: self.cons_symb = [] else: self.cons_symb = [x.symbol for x in problem.constraints] def update(self, message: Message) -> None: """Update the archiver with the new data. Args: message (Message): Message from the publisher. """ if ( message.topic == TerminatorMessageTopics.GENERATION # NOQA: PLR1714 or message.topic == SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS ): super().update(message) return data = message.value data = data.with_columns(generation=self.generation_number) if type(data) is not pl.DataFrame: raise ValueError("Data should be a polars DataFrame") if self.cons_symb: feasible_mask = (data[self.cons_symb] <= 0).to_numpy().all(axis=1) data = data.filter(feasible_mask) if self.solutions is None: non_dom_mask = non_dominated(data[self.targets].to_numpy()) self.solutions = data.filter(non_dom_mask) else: to_add = data.filter(non_dominated(data[self.targets].to_numpy())) mask1, mask2 = non_dominated_merge(self.solutions[self.targets].to_numpy(), to_add[self.targets].to_numpy()) self.solutions = pl.concat([self.solutions.filter(mask1), to_add.filter(mask2)]) ``` ##### __init__ ``` __init__(*, problem: Problem, publisher: Publisher) ``` Initialize the archiver. Parameters: | Name | Type | Description | Default | | ----------- | ----------- | ------------------------- | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | | `publisher` | `Publisher` | The publisher object. | *required* | Source code in `desdeo/emo/hooks/archivers.py` ``` def __init__(self, *, problem: Problem, publisher: Publisher): """Initialize the archiver. Args: problem (Problem): The problem being solved. publisher (Publisher): The publisher object. """ super().__init__(problem=problem, publisher=publisher) self.targets = [f"{x.symbol}_min" for x in problem.objectives] if problem.constraints is None: self.cons_symb = [] else: self.cons_symb = [x.symbol for x in problem.constraints] ``` ##### update ``` update(message: Message) -> None ``` Update the archiver with the new data. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------- | ---------- | | `message` | `Message` | Message from the publisher. | *required* | Source code in `desdeo/emo/hooks/archivers.py` ``` def update(self, message: Message) -> None: """Update the archiver with the new data. Args: message (Message): Message from the publisher. """ if ( message.topic == TerminatorMessageTopics.GENERATION # NOQA: PLR1714 or message.topic == SelectorMessageTopics.SELECTED_VERBOSE_OUTPUTS ): super().update(message) return data = message.value data = data.with_columns(generation=self.generation_number) if type(data) is not pl.DataFrame: raise ValueError("Data should be a polars DataFrame") if self.cons_symb: feasible_mask = (data[self.cons_symb] <= 0).to_numpy().all(axis=1) data = data.filter(feasible_mask) if self.solutions is None: non_dom_mask = non_dominated(data[self.targets].to_numpy()) self.solutions = data.filter(non_dom_mask) else: to_add = data.filter(non_dominated(data[self.targets].to_numpy())) mask1, mask2 = non_dominated_merge(self.solutions[self.targets].to_numpy(), to_add[self.targets].to_numpy()) self.solutions = pl.concat([self.solutions.filter(mask1), to_add.filter(mask2)]) ``` ### desdeo.explanations.explainer Explainers are defined here. #### ShapExplainer Defines a SHAP explainer for reference point based methods. Source code in `desdeo/explanations/explainer.py` ``` class ShapExplainer: """Defines a SHAP explainer for reference point based methods.""" def __init__(self, problem_data: pl.DataFrame, input_symbols: list[str], output_symbols: list[str]): """Initialize the explainer. Initializes the explainer with given data, and input and output symbols. The data should contain the columns listed in the input and output symbols. This data is then used to simulate the inputs and outputs of an (interactive) multiobjective optimization method, which is used to explain the relation of its inputs and outputs using SHAP values. Note: The `data` can be generated by for a reference point based based by, e.g., randomly sampling the input space and then evaluating the methods with the sampled inputs to generate outputs. Args: problem_data (pl.DataFrame): the data to simulate the input and outputs of a multiobjective optimization method. input_symbols (list[str]): the input symbols present in `data`. These symbols represent the inputs to the method. output_symbols (list[str]): the output symbols present in `data`. These symbols represent the outputs of the method. """ self.data = problem_data self.input_symbols = input_symbols self.output_symbols = output_symbols self.input_array = self.data[self.input_symbols].to_numpy() self.output_array = self.data[self.output_symbols].to_numpy() self.to_output_tree = cKDTree(self.input_array) self.explainer = None def setup(self, background_data: pl.DataFrame): """Setup the explainer. Setups the SHAP explainer with the given background data. The background data should have the columns `self.input_symbols`. The background data is used as the background (or missing data) when computing SHAP values. The mean (or expected values) of the background data's output (`self.output_symbols`) will determine the baseline of the SHAP values. Note: To generate a dataset with meaningful expected values, e.g., in case the SHAP values are better understood by relating them to a specific baseline, see `desdeo.explanations.generate_biased_mean_data`. Args: background_data (pl.DataFrame): the background data. """ self.explainer = shap.Explainer( self.evaluate, masker=background_data[self.input_symbols].to_numpy(), ) def evaluate(self, evaluate_array: np.ndarray) -> np.ndarray: """Evaluates the multiobjective optimization method represented by the data. Note: Evaluation happens by finding the closest matching input array in the `self.input_array` and then using that value's corresponding output as the evaluation result. Closest means lowest Euclidean distance. Args: evaluate_array (np.ndarray): the inputs to the method represented by the data. Can be either a single input, or an array of multiple inputs. Used mainly by `self.explain_input`. Returns: np.ndarray: the evaluated output(s) corresponding to the input data. """ _, indices = self.to_output_tree.query(evaluate_array) return self.output_array[indices] def explain_input(self, to_be_explained: pl.DataFrame) -> dict: """Explain an input and produces SHAP values. Args: to_be_explained (pl.DataFrame): the input to be explained. The dataframe must have the columns defined in `self.input_symbols`. Returns: dict: the key 'shaps' corresponds to the computed SHAP values for the input, the key 'base_values' is the baseline the SHAP values were computed against, and the key 'data' is the input the SHAP values were computed for. """ _to_be_explained = to_be_explained[self.input_symbols].to_numpy() return self.explainer(_to_be_explained) ``` ##### __init__ ``` __init__( problem_data: DataFrame, input_symbols: list[str], output_symbols: list[str], ) ``` Initialize the explainer. Initializes the explainer with given data, and input and output symbols. The data should contain the columns listed in the input and output symbols. This data is then used to simulate the inputs and outputs of an (interactive) multiobjective optimization method, which is used to explain the relation of its inputs and outputs using SHAP values. Note The `data` can be generated by for a reference point based based by, e.g., randomly sampling the input space and then evaluating the methods with the sampled inputs to generate outputs. Parameters: | Name | Type | Description | Default | | ---------------- | ----------- | -------------------------------------------------------------------------------------- | ---------- | | `problem_data` | `DataFrame` | the data to simulate the input and outputs of a multiobjective optimization method. | *required* | | `input_symbols` | `list[str]` | the input symbols present in data. These symbols represent the inputs to the method. | *required* | | `output_symbols` | `list[str]` | the output symbols present in data. These symbols represent the outputs of the method. | *required* | Source code in `desdeo/explanations/explainer.py` ``` def __init__(self, problem_data: pl.DataFrame, input_symbols: list[str], output_symbols: list[str]): """Initialize the explainer. Initializes the explainer with given data, and input and output symbols. The data should contain the columns listed in the input and output symbols. This data is then used to simulate the inputs and outputs of an (interactive) multiobjective optimization method, which is used to explain the relation of its inputs and outputs using SHAP values. Note: The `data` can be generated by for a reference point based based by, e.g., randomly sampling the input space and then evaluating the methods with the sampled inputs to generate outputs. Args: problem_data (pl.DataFrame): the data to simulate the input and outputs of a multiobjective optimization method. input_symbols (list[str]): the input symbols present in `data`. These symbols represent the inputs to the method. output_symbols (list[str]): the output symbols present in `data`. These symbols represent the outputs of the method. """ self.data = problem_data self.input_symbols = input_symbols self.output_symbols = output_symbols self.input_array = self.data[self.input_symbols].to_numpy() self.output_array = self.data[self.output_symbols].to_numpy() self.to_output_tree = cKDTree(self.input_array) self.explainer = None ``` ##### evaluate ``` evaluate(evaluate_array: ndarray) -> np.ndarray ``` Evaluates the multiobjective optimization method represented by the data. Note Evaluation happens by finding the closest matching input array in the `self.input_array` and then using that value's corresponding output as the evaluation result. Closest means lowest Euclidean distance. Parameters: | Name | Type | Description | Default | | ---------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `evaluate_array` | `ndarray` | the inputs to the method represented by the data. Can be either a single input, or an array of multiple inputs. Used mainly by self.explain_input. | *required* | Returns: | Type | Description | | --------- | -------------------------------------------------------------------- | | `ndarray` | np.ndarray: the evaluated output(s) corresponding to the input data. | Source code in `desdeo/explanations/explainer.py` ``` def evaluate(self, evaluate_array: np.ndarray) -> np.ndarray: """Evaluates the multiobjective optimization method represented by the data. Note: Evaluation happens by finding the closest matching input array in the `self.input_array` and then using that value's corresponding output as the evaluation result. Closest means lowest Euclidean distance. Args: evaluate_array (np.ndarray): the inputs to the method represented by the data. Can be either a single input, or an array of multiple inputs. Used mainly by `self.explain_input`. Returns: np.ndarray: the evaluated output(s) corresponding to the input data. """ _, indices = self.to_output_tree.query(evaluate_array) return self.output_array[indices] ``` ##### explain_input ``` explain_input(to_be_explained: DataFrame) -> dict ``` Explain an input and produces SHAP values. Parameters: | Name | Type | Description | Default | | ----------------- | ----------- | --------------------------------------------------------------------------------------------- | ---------- | | `to_be_explained` | `DataFrame` | the input to be explained. The dataframe must have the columns defined in self.input_symbols. | *required* | Returns: | Name | Type | Description | | ------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dict` | `dict` | the key 'shaps' corresponds to the computed SHAP values for the input, the key 'base_values' is the baseline the SHAP values were computed against, and the key 'data' is the input the SHAP values were computed for. | Source code in `desdeo/explanations/explainer.py` ``` def explain_input(self, to_be_explained: pl.DataFrame) -> dict: """Explain an input and produces SHAP values. Args: to_be_explained (pl.DataFrame): the input to be explained. The dataframe must have the columns defined in `self.input_symbols`. Returns: dict: the key 'shaps' corresponds to the computed SHAP values for the input, the key 'base_values' is the baseline the SHAP values were computed against, and the key 'data' is the input the SHAP values were computed for. """ _to_be_explained = to_be_explained[self.input_symbols].to_numpy() return self.explainer(_to_be_explained) ``` ##### setup ``` setup(background_data: DataFrame) ``` Setup the explainer. Setups the SHAP explainer with the given background data. The background data should have the columns `self.input_symbols`. The background data is used as the background (or missing data) when computing SHAP values. The mean (or expected values) of the background data's output (`self.output_symbols`) will determine the baseline of the SHAP values. Note To generate a dataset with meaningful expected values, e.g., in case the SHAP values are better understood by relating them to a specific baseline, see `desdeo.explanations.generate_biased_mean_data`. Parameters: | Name | Type | Description | Default | | ----------------- | ----------- | -------------------- | ---------- | | `background_data` | `DataFrame` | the background data. | *required* | Source code in `desdeo/explanations/explainer.py` ``` def setup(self, background_data: pl.DataFrame): """Setup the explainer. Setups the SHAP explainer with the given background data. The background data should have the columns `self.input_symbols`. The background data is used as the background (or missing data) when computing SHAP values. The mean (or expected values) of the background data's output (`self.output_symbols`) will determine the baseline of the SHAP values. Note: To generate a dataset with meaningful expected values, e.g., in case the SHAP values are better understood by relating them to a specific baseline, see `desdeo.explanations.generate_biased_mean_data`. Args: background_data (pl.DataFrame): the background data. """ self.explainer = shap.Explainer( self.evaluate, masker=background_data[self.input_symbols].to_numpy(), ) ``` ### desdeo.explanations.lagrange Utilities for working with Lagrange multipliers in explainable multiobjective optimization. #### compute_tradeoffs ``` compute_tradeoffs( filtered_multipliers: dict[str, float] | None, ) -> dict[str, dict[str, float]] | None ``` Compute a tradeoff matrix from filtered Lagrange multipliers. Tradeoffs represent marginal rates of substitution between objectives. For objectives *i* and *j*: `tradeoff[i][j] = -lambda_j / lambda_i`. Parameters: | Name | Type | Description | Default | | ---------------------- | ------------------ | ----------- | ------------------------------------------------------------------------------------------------------------------ | | `filtered_multipliers` | \`dict[str, float] | None\` | Dict mapping objective keys to their multiplier values. Typically the output of :func:filter_lagrange_multipliers. | Returns: | Type | Description | | ------------------------------- | ----------- | | \`dict\[str, dict[str, float]\] | None\` | | \`dict\[str, dict[str, float]\] | None\` | | \`dict\[str, dict[str, float]\] | None\` | Source code in `desdeo/explanations/lagrange.py` ``` def compute_tradeoffs( filtered_multipliers: dict[str, float] | None, ) -> dict[str, dict[str, float]] | None: """Compute a tradeoff matrix from filtered Lagrange multipliers. Tradeoffs represent marginal rates of substitution between objectives. For objectives *i* and *j*: ``tradeoff[i][j] = -lambda_j / lambda_i``. Args: filtered_multipliers: Dict mapping objective keys to their multiplier values. Typically the output of :func:`filter_lagrange_multipliers`. Returns: A nested dict where ``result[i][j]`` is the tradeoff of improving objective *i* on objective *j*. Diagonal entries are 1.0. Returns ``None`` if input is ``None`` or empty. """ if not filtered_multipliers: return None objectives = list(filtered_multipliers.keys()) tradeoffs: dict[str, dict[str, float]] = {} for obj_i in objectives: tradeoffs[obj_i] = {} lambda_i = filtered_multipliers[obj_i] if lambda_i == 0: for obj_j in objectives: tradeoffs[obj_i][obj_j] = 0.0 if obj_i != obj_j else 1.0 continue for obj_j in objectives: if obj_i == obj_j: tradeoffs[obj_i][obj_j] = 1.0 else: lambda_j = filtered_multipliers[obj_j] tradeoffs[obj_i][obj_j] = -lambda_j / lambda_i return tradeoffs ``` #### determine_active_objectives ``` determine_active_objectives( lagrange_multipliers: list[dict[str, float] | None], constraint_values: list[dict[str, float] | None] | None = None, objective_symbols: list[str] | None = None, threshold: float = 1e-05, ) -> list[list[str]] ``` Determine which objectives are active (binding) for each solution. An objective is considered active if its corresponding constraint is binding (constraint value >= 0) or, when constraint values are not available, if its multiplier magnitude exceeds a threshold. Parameters: | Name | Type | Description | Default | | ---------------------- | ------------------------ | ---------------------------------------------------------- | ---------------------------------------------------- | | `lagrange_multipliers` | \`list\[dict[str, float] | None\]\` | List of filtered multiplier dicts, one per solution. | | `constraint_values` | \`list\[dict[str, float] | None\] | None\` | | `objective_symbols` | \`list[str] | None\` | Optional list of known objective symbols. | | `threshold` | `float` | Multiplier magnitude threshold for the fallback heuristic. | `1e-05` | Returns: | Type | Description | | ----------------- | ------------------------------------------------------------------ | | `list[list[str]]` | A list of lists, where each inner list contains the symbols of the | | `list[list[str]]` | active objectives for the corresponding solution. | Source code in `desdeo/explanations/lagrange.py` ``` def determine_active_objectives( lagrange_multipliers: list[dict[str, float] | None], constraint_values: list[dict[str, float] | None] | None = None, objective_symbols: list[str] | None = None, threshold: float = 1e-5, ) -> list[list[str]]: """Determine which objectives are active (binding) for each solution. An objective is considered active if its corresponding constraint is binding (constraint value >= 0) or, when constraint values are not available, if its multiplier magnitude exceeds a threshold. Args: lagrange_multipliers: List of filtered multiplier dicts, one per solution. constraint_values: Optional list of filtered constraint value dicts. objective_symbols: Optional list of known objective symbols. threshold: Multiplier magnitude threshold for the fallback heuristic. Returns: A list of lists, where each inner list contains the symbols of the active objectives for the corresponding solution. """ active_objectives: list[list[str]] = [] if constraint_values and objective_symbols: for constraint_dict in constraint_values: if constraint_dict is None: active_objectives.append([]) continue active = [obj for obj, value in constraint_dict.items() if obj in objective_symbols and value >= 0] active_objectives.append(active) elif objective_symbols: for multiplier_dict in lagrange_multipliers: if multiplier_dict is None: active_objectives.append([]) continue active = [obj for obj in objective_symbols if abs(multiplier_dict.get(obj, 0.0)) > threshold] active_objectives.append(active) else: for multiplier_dict in lagrange_multipliers: if multiplier_dict is None: active_objectives.append([]) continue active = [obj for obj, value in multiplier_dict.items() if abs(value) > threshold] active_objectives.append(active) return active_objectives ``` #### filter_constraint_values ``` filter_constraint_values( constraint_values: dict[str, float], objective_symbols: list[str] | None = None, ) -> dict[str, float] ``` Filter constraint values to keep one representative per objective. Same grouping logic as :func:`filter_lagrange_multipliers` but applied to constraint values. Used to determine which constraints are active. Parameters: | Name | Type | Description | Default | | ------------------- | ------------------ | --------------------------------------------- | ------------------------------------------------ | | `constraint_values` | `dict[str, float]` | Raw constraint value dict from SolverResults. | *required* | | `objective_symbols` | \`list[str] | None\` | Optional list of objective symbols for grouping. | Returns: | Type | Description | | ------------------ | ------------------------------------------------------------------- | | `dict[str, float]` | A dict mapping each objective key to its filtered constraint value. | Source code in `desdeo/explanations/lagrange.py` ``` def filter_constraint_values( constraint_values: dict[str, float], objective_symbols: list[str] | None = None, ) -> dict[str, float]: """Filter constraint values to keep one representative per objective. Same grouping logic as :func:`filter_lagrange_multipliers` but applied to constraint values. Used to determine which constraints are active. Args: constraint_values: Raw constraint value dict from SolverResults. objective_symbols: Optional list of objective symbols for grouping. Returns: A dict mapping each objective key to its filtered constraint value. """ grouped: dict[str, list[tuple[str, float]]] = defaultdict(list) for key, value in constraint_values.items(): if objective_symbols is None: match = re.search(r"f_(\d+)", key) if match: f_i = match.group(1) grouped[f_i].append((key, value)) else: for symbol in objective_symbols: if symbol in key: grouped[symbol].append((key, value)) break filtered: dict[str, float] = {} for obj_key, entries in grouped.items(): preferred = next((entry for entry in entries if not entry[0].endswith("eq")), None) if preferred is None and entries: preferred = entries[0] if preferred: key = obj_key if (objective_symbols is not None and obj_key in objective_symbols) else preferred[0] filtered[key] = preferred[1] return filtered ``` #### filter_lagrange_multipliers ``` filter_lagrange_multipliers( lagrange_multipliers: dict[str, float], objective_symbols: list[str] | None = None, ) -> dict[str, float] ``` Filter raw Lagrange multipliers to keep one representative per objective. Solver results may contain multiple multiplier entries per objective (e.g., from equality and inequality constraints). This function groups them and selects a preferred one (non-equality constraint preferred). Parameters: | Name | Type | Description | Default | | ---------------------- | ------------------ | --------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `lagrange_multipliers` | `dict[str, float]` | Raw multiplier dict from SolverResults. | *required* | | `objective_symbols` | \`list[str] | None\` | If provided, use these to group multipliers by objective symbol. Otherwise, group by f\_{index} pattern. | Returns: | Type | Description | | ------------------ | ------------------------------------------------------------------- | | `dict[str, float]` | A dict mapping each objective key to its filtered multiplier value. | | `dict[str, float]` | Missing objectives are assigned 0.0. | Source code in `desdeo/explanations/lagrange.py` ``` def filter_lagrange_multipliers( # noqa: C901 lagrange_multipliers: dict[str, float], objective_symbols: list[str] | None = None, ) -> dict[str, float]: """Filter raw Lagrange multipliers to keep one representative per objective. Solver results may contain multiple multiplier entries per objective (e.g., from equality and inequality constraints). This function groups them and selects a preferred one (non-equality constraint preferred). Args: lagrange_multipliers: Raw multiplier dict from SolverResults. objective_symbols: If provided, use these to group multipliers by objective symbol. Otherwise, group by ``f_{index}`` pattern. Returns: A dict mapping each objective key to its filtered multiplier value. Missing objectives are assigned 0.0. """ grouped: dict[str, list[tuple[str, float]]] = defaultdict(list) for key, value in lagrange_multipliers.items(): if objective_symbols is None: match = re.search(r"f_(\d+)", key) if match: f_i = match.group(1) grouped[f_i].append((key, value)) else: for symbol in objective_symbols: if symbol in key: grouped[symbol].append((key, value)) break filtered: dict[str, float] = {} for obj_key, entries in grouped.items(): # Prefer non-"eq" constraints preferred = next((entry for entry in entries if not entry[0].endswith("eq")), None) if preferred is None and entries: preferred = entries[0] if preferred: # Use the symbol as key if available key = obj_key if (objective_symbols is not None and obj_key in objective_symbols) else preferred[0] filtered[key] = preferred[1] # Ensure every objective has an entry (default 0.0) if objective_symbols is not None: for symbol in objective_symbols: if symbol not in filtered: filtered[symbol] = 0.0 else: max_index = -1 for key in filtered: match = re.search(r"f_(\d+)", key) if match: max_index = max(max_index, int(match.group(1))) for i in range(max_index + 1): key = f"f_{i}" if key not in filtered: filtered[key] = 0.0 return filtered ``` ### desdeo.explanations.utils Utilities specific to explainable multiobjective optimization. #### generate_biased_mean_data ``` generate_biased_mean_data( data: ndarray, target_means: ndarray, min_size: int = 2, max_size: int | None = None, solver: str = "SCIP", ) -> list | None ``` Finds a subset of the provided data that has a mean value close to provided target values. Finds a subset of the provided data that has a mean value close to the provided target values. Formulates a mixed-integer quadratic programming problem to find a subset of `data` with a mean as close as possible to `target_values` and a size between `min_size` and `max_size`. In other words, the following problems is solved: , where (n) is the number of rows in `data`, (m) is the number of columns in `data`, and (k) is the size of the subset. Notice that the closeness to the target means is based on the Euclidean distance. Note Be mindful that this functions can take a long time with a very large data set and large upper bound for the desired subset. Parameters: | Name | Type | Description | Default | | -------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `data` | `ndarray` | the data from which to generate the subset with a biased mean. Should be a 2D array with each row representing a sample and each column the value of the variables in the sample. | *required* | | `target_means` | `ndarray` | the target mean values for each column the generated subset should have values close to. | *required* | | `min_size` | `int` | the minimum size of the generated subset. Defaults to 2. | `2` | | `max_size` | \`int | None\` | the maximum size of the generated subset. If None, then the maximum size is bound by the numbers of rows in data. Defaults to None. | | `solver` | `str` | the selected solver to be used by cvxpy. The solver should support mixed-integer quadratic programming. Defaults to "SCIP". | `'SCIP'` | Returns: | Type | Description | | ------ | ----------- | | \`list | None\` | Source code in `desdeo/explanations/utils.py` ``` def generate_biased_mean_data( data: np.ndarray, target_means: np.ndarray, min_size: int = 2, max_size: int | None = None, solver: str = "SCIP" ) -> list | None: r"""Finds a subset of the provided data that has a mean value close to provided target values. Finds a subset of the provided data that has a mean value close to the provided target values. Formulates a mixed-integer quadratic programming problem to find a subset of `data` with a mean as close as possible to `target_values` and a size between `min_size` and `max_size`. In other words, the following problems is solved: \begin{align} &\min_{\mathbf{x}} & f(\mathbf{x}) & = \sum_{i=1}^m \left[ \left(\frac{1}{k} \sum_{j=1}^n x_j \times \text{data}_j\right)_i - \text{target}_i \right]^2 \\ &\text{s.t.,} & k & = \sum_{i=1}^n x_i,\\ & & k & \leq \text{max_size},\\ & & k & \geq \text{min_size},\\ \end{align}, where $n$ is the number of rows in `data`, $m$ is the number of columns in `data`, and $k$ is the size of the subset. Notice that the closeness to the target means is based on the Euclidean distance. Note: Be mindful that this functions can take a long time with a very large data set and large upper bound for the desired subset. Args: data (np.ndarray): the data from which to generate the subset with a biased mean. Should be a 2D array with each row representing a sample and each column the value of the variables in the sample. target_means (np.ndarray): the target mean values for each column the generated subset should have values close to. min_size (int, optional): the minimum size of the generated subset. Defaults to 2. max_size (int | None, optional): the maximum size of the generated subset. If None, then the maximum size is bound by the numbers of rows in `data`. Defaults to None. solver (str, optional): the selected solver to be used by cvxpy. The solver should support mixed-integer quadratic programming. Defaults to "SCIP". Returns: list | None: the indices of the samples of the generated subset respect to `data`, i.e., the generated subset is `data[indices]`. If optimization is not successful, returns None instead. """ # Number of rows and columns n_rows, n_cols = data.shape max_size = n_rows if max_size is None else max_size # Big M used to penalize the auxiliary variable z big_m = data.max(axis=0) # Binary variables to select rows from the data x = cp.Variable(n_rows, boolean=True) # Auxiliary variables, z represents the mean. phi is the weighted sum of the data (weighted by x) z = cp.Variable(n_cols) phi = cp.Variable((n_rows, n_cols)) # The objective function, squared values of the difference between the mean # of the currently selected subset and the target values. objective = cp.sum_squares(z - target_means) # Define the constraints constraints = [ # Sets the value of phi *[cp.sum(phi[:, col]) == cp.sum(cp.multiply(x, data[:, col])) for col in range(n_cols)], # Constraints the values of phi using big M, in practice setting z to be the mean values *[phi[:, col] <= cp.multiply(big_m[col], x) for col in range(n_cols)], *[phi[:, col] <= z[col] for col in range(n_cols)], *[phi[:, col] >= z[col] - cp.multiply(big_m[col], 1 - x) for col in range(n_cols)], phi >= 0, # Bounds the size of the set: min_size <= k <= max_size cp.sum(x) >= min_size, cp.sum(x) <= max_size, ] # Create the problem model problem = cp.Problem(cp.Minimize(objective), constraints) # Solve the problem problem.solve(solver=solver) # Return the indices of the found subset return [i for i in range(n_rows) if x.value[i] == 1] ``` ### desdeo.gdm.gdmtools This module contains tools for group decision making such as manipulating set of preferences. #### agg_aspbounds ``` agg_aspbounds( po_list: list[dict[str, float]], problem: Problem ) -> tuple[dict[str, float], dict[str, float]] ``` Aggregate a set of preferences into shared aspiration levels and bounds. For each objective, the aggregated aspiration level is the most optimistic value across the given preferences (the maximum for objectives to be maximized, the minimum for objectives to be minimized), while the aggregated bound is the least optimistic value. Parameters: | Name | Type | Description | Default | | --------- | ------------------------ | ------------------------------------------------------------------------------------------------------------- | ---------- | | `po_list` | `list[dict[str, float]]` | a list of preferences, where each preference maps objective symbols to values. | *required* | | `problem` | `Problem` | the problem the preferences relate to. Used to determine the objective symbols and whether each is maximized. | *required* | Returns: | Type | Description | | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[dict[str, float], dict[str, float]]` | tuple\[dict[str, float], dict[str, float]\]: the aggregated aspiration levels and the aggregated bounds, each mapping objective symbols to values. | Source code in `desdeo/gdm/gdmtools.py` ``` def agg_aspbounds(po_list: list[dict[str, float]], problem: Problem) -> tuple[dict[str, float], dict[str, float]]: """Aggregate a set of preferences into shared aspiration levels and bounds. For each objective, the aggregated aspiration level is the most optimistic value across the given preferences (the maximum for objectives to be maximized, the minimum for objectives to be minimized), while the aggregated bound is the least optimistic value. Args: po_list (list[dict[str, float]]): a list of preferences, where each preference maps objective symbols to values. problem (Problem): the problem the preferences relate to. Used to determine the objective symbols and whether each is maximized. Returns: tuple[dict[str, float], dict[str, float]]: the aggregated aspiration levels and the aggregated bounds, each mapping objective symbols to values. """ agg_aspirations = {} agg_bounds = {} for obj in problem.objectives: if obj.maximize: agg_aspirations.update({obj.symbol: max(s[obj.symbol] for s in po_list)}) agg_bounds.update({obj.symbol: min(s[obj.symbol] for s in po_list)}) else: agg_aspirations.update({obj.symbol: min(s[obj.symbol] for s in po_list)}) agg_bounds.update({obj.symbol: max(s[obj.symbol] for s in po_list)}) return agg_aspirations, agg_bounds ``` #### dict_of_rps_to_list_of_rps ``` dict_of_rps_to_list_of_rps( reference_points: dict[str, dict[str, float]], ) -> list[dict[str, float]] ``` Convert a dict of preferences keyed by decision maker into an ordered list of preferences. Source code in `desdeo/gdm/gdmtools.py` ``` def dict_of_rps_to_list_of_rps(reference_points: dict[str, dict[str, float]]) -> list[dict[str, float]]: """Convert a dict of preferences keyed by decision maker into an ordered list of preferences.""" return list(reference_points.values()) ``` #### list_of_rps_to_dict_of_rps ``` list_of_rps_to_dict_of_rps( reference_points: list[dict[str, float]], ) -> dict[str, dict[str, float]] ``` Convert an ordered list of preferences into a dict keyed by decision maker (`DM1`, `DM2`, ...). Source code in `desdeo/gdm/gdmtools.py` ``` def list_of_rps_to_dict_of_rps(reference_points: list[dict[str, float]]) -> dict[str, dict[str, float]]: """Convert an ordered list of preferences into a dict keyed by decision maker (``DM1``, ``DM2``, ...).""" return {f"DM{i + 1}": rp for i, rp in enumerate(reference_points)} ``` #### scale_delta ``` scale_delta(problem: Problem, d: float) -> dict[str, float] ``` Scale a step size into a per-objective delta based on the objective ranges. For each objective, the delta has magnitude equal to the fraction `d` of the objective's range, i.e. the distance between the ideal and nadir points. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem whose ideal and nadir points define the objective ranges. | *required* | | `d` | `float` | the fraction of each objective's range to use as the delta. | *required* | Returns: | Type | Description | | ------------------ | ------------------------------------------------------------------------- | | `dict[str, float]` | dict\[str, float\]: a mapping from objective symbols to the scaled delta. | Source code in `desdeo/gdm/gdmtools.py` ``` def scale_delta(problem: Problem, d: float) -> dict[str, float]: """Scale a step size into a per-objective delta based on the objective ranges. For each objective, the delta has magnitude equal to the fraction `d` of the objective's range, i.e. the distance between the ideal and nadir points. Args: problem (Problem): the problem whose ideal and nadir points define the objective ranges. d (float): the fraction of each objective's range to use as the delta. Returns: dict[str, float]: a mapping from objective symbols to the scaled delta. """ delta = {} ideal = problem.get_ideal_point() nadir = problem.get_nadir_point() for obj in problem.objectives: if obj.maximize: delta.update({obj.symbol: d * (ideal[obj.symbol] - nadir[obj.symbol])}) else: delta.update({obj.symbol: d * (nadir[obj.symbol] - ideal[obj.symbol])}) return delta ``` ### desdeo.gdm.voting_rules This module contains voting rules for group decision making such as majority rule. #### consensus_rule ``` consensus_rule( votes: dict[str, int], min_votes: int ) -> list[int] ``` Choose all options that have at least min_votes votes. Parameters: | Name | Type | Description | Default | | ----------- | ---------------- | ------------------------------------------------------------------ | ---------- | | `votes` | `dict[str, int]` | A dictionary mapping voter IDs to their votes. | *required* | | `min_votes` | `int` | The minimum number of votes required for an option to be selected. | *required* | Source code in `desdeo/gdm/voting_rules.py` ``` def consensus_rule(votes: dict[str, int], min_votes: int) -> list[int]: """Choose all options that have at least min_votes votes. Args: votes (dict[str, int]): A dictionary mapping voter IDs to their votes. min_votes (int): The minimum number of votes required for an option to be selected. """ if min_votes <= 0: raise ValueError("min_votes must be greater than 0.") if min_votes > len(votes): raise ValueError("min_votes cannot be greater than the number of voters.") counts = Counter(votes.values()) return [vote for vote, c in counts.items() if c >= min_votes] ``` #### majority_rule ``` majority_rule(votes: dict[str, int]) -> int | None ``` Choose the option that has more than half of the votes. Parameters: | Name | Type | Description | Default | | ------- | ---------------- | ---------------------------------------------- | ---------- | | `votes` | `dict[str, int]` | A dictionary mapping voter IDs to their votes. | *required* | Returns: | Type | Description | | ----- | ----------- | | \`int | None\` | Source code in `desdeo/gdm/voting_rules.py` ``` def majority_rule(votes: dict[str, int]) -> int | None: """Choose the option that has more than half of the votes. Args: votes (dict[str, int]): A dictionary mapping voter IDs to their votes. Returns: int | None: The option that has more than half of the votes, or None if no such option exists. """ counts = Counter(votes.values()) all_votes = sum(counts.values()) for vote, c in counts.items(): if c > all_votes // 2: return vote return None ``` #### plurality_rule ``` plurality_rule(votes: dict[str, int]) -> list[int] ``` Choose the option that has the most votes. Parameters: | Name | Type | Description | Default | | ------- | ---------------- | ---------------------------------------------- | ---------- | | `votes` | `dict[str, int]` | A dictionary mapping voter IDs to their votes. | *required* | Returns: | Type | Description | | ----------- | --------------------------------------------------------------------------- | | `list[int]` | list\[int\]: A list of options that have the most votes (in case of a tie). | Source code in `desdeo/gdm/voting_rules.py` ``` def plurality_rule(votes: dict[str, int]) -> list[int]: """Choose the option that has the most votes. Args: votes (dict[str, int]): A dictionary mapping voter IDs to their votes. Returns: list[int]: A list of options that have the most votes (in case of a tie). """ counts = Counter(votes.values()) max_votes = max(counts.values()) return [vote for vote, c in counts.items() if c == max_votes] ``` ### desdeo.gdm.score_bands Implements a interactive SCORE bands based GDM. #### SCOREBandsGDMConfig Bases: `BaseModel` Configuration for the SCORE bands based GDM. Source code in `desdeo/gdm/score_bands.py` ``` class SCOREBandsGDMConfig(BaseModel): """Configuration for the SCORE bands based GDM.""" model_config = ConfigDict(arbitrary_types_allowed=True) score_bands_config: SCOREBandsConfig = Field(default_factory=SCOREBandsConfig) """Configuration for the SCORE bands method.""" minimum_votes: int = Field(default=1, gt=0) """Minimum number of votes required to select a cluster.""" from_iteration: int | None """The iteration number from which to consider the clusters. Set to None if method is initializing.""" ``` ##### from_iteration ``` from_iteration: int | None ``` The iteration number from which to consider the clusters. Set to None if method is initializing. ##### minimum_votes ``` minimum_votes: int = Field(default=1, gt=0) ``` Minimum number of votes required to select a cluster. ##### score_bands_config ``` score_bands_config: SCOREBandsConfig = Field( default_factory=SCOREBandsConfig ) ``` Configuration for the SCORE bands method. #### SCOREBandsGDMResult Bases: `BaseModel` Result of the SCORE bands based GDM. Source code in `desdeo/gdm/score_bands.py` ``` class SCOREBandsGDMResult(BaseModel): """Result of the SCORE bands based GDM.""" model_config = ConfigDict(arbitrary_types_allowed=True) votes: dict[str, int] | None = Field(default=None) """The votes given by the decision makers.""" score_bands_result: SCOREBandsResult """Result of the SCORE bands method.""" relevant_ids: list[int] """IDs of the relevant solutions in the current iteration. Assumes that data is not modified between iterations.""" # If the data keeps changing, we need to store the actual data instead of just the IDs. iteration: int previous_iteration: int | None """The previous iteration number, if any.""" ``` ##### previous_iteration ``` previous_iteration: int | None ``` The previous iteration number, if any. ##### relevant_ids ``` relevant_ids: list[int] ``` IDs of the relevant solutions in the current iteration. Assumes that data is not modified between iterations. ##### score_bands_result ``` score_bands_result: SCOREBandsResult ``` Result of the SCORE bands method. ##### votes ``` votes: dict[str, int] | None = Field(default=None) ``` The votes given by the decision makers. #### score_bands_gdm ``` score_bands_gdm( data: DataFrame, config: SCOREBandsGDMConfig, state: list[SCOREBandsGDMResult], votes: dict[str, int] | None = None, ) -> list[SCOREBandsGDMResult] ``` Run the SCORE bands based interactive GDM. Parameters: | Name | Type | Description | Default | | -------- | --------------------------- | ----------------------------------------------------------------- | ------------------------------------------------- | | `data` | `DataFrame` | The data to run the GDM on. | *required* | | `config` | `SCOREBandsGDMConfig` | Configuration for the GDM. | *required* | | `state` | `list[SCOREBandsGDMResult]` | List of previous state of the GDM. Empty list if first iteration. | *required* | | `votes` | \`dict[str, int] | None\` | Votes from the decision makers. Defaults to None. | Raises: | Type | Description | | ------------ | ------------------------------------------------- | | `ValueError` | Both state and votes must be provided or neither. | Returns: | Type | Description | | --------------------------- | ---------------------------------------------------------- | | `list[SCOREBandsGDMResult]` | list\[SCOREBandsGDMResult\]: The updated state of the GDM. | Source code in `desdeo/gdm/score_bands.py` ``` def score_bands_gdm( data: pl.DataFrame, config: SCOREBandsGDMConfig, state: list[SCOREBandsGDMResult], votes: dict[str, int] | None = None, ) -> list[SCOREBandsGDMResult]: """Run the SCORE bands based interactive GDM. Args: data (pl.DataFrame): The data to run the GDM on. config (SCOREBandsGDMConfig): Configuration for the GDM. state (list[SCOREBandsGDMResult]): List of previous state of the GDM. Empty list if first iteration. votes (dict[str, int] | None, optional): Votes from the decision makers. Defaults to None. Raises: ValueError: Both state and votes must be provided or neither. Returns: list[SCOREBandsGDMResult]: The updated state of the GDM. """ if bool(state) != bool(votes): raise ValueError("Both state and votes must be provided or neither.") if votes is None: # First iteration. No votes yet. score_bands_result = score_json(data, config.score_bands_config) return [ SCOREBandsGDMResult( score_bands_result=score_bands_result, relevant_ids=list(range(len(data))), iteration=1, previous_iteration=None, ) ] if not state: raise ValueError("State must be provided if votes are provided.") if config.from_iteration is None: raise ValueError("from_iteration must be set in the config for subsequent iterations.") winning_clusters = consensus_rule(votes, config.minimum_votes) index_column_name = "index" if index_column_name in data.columns: index_column_name = "index_" cluster_column_name = "cluster" if cluster_column_name in data.columns: cluster_column_name = "cluster_" current_iteration = state[-1].iteration + 1 clusters = state[config.from_iteration - 1].score_bands_result.clusters relevant_data = ( data.with_row_index(name=index_column_name) # Add index column .filter( pl.col(index_column_name).is_in(state[config.from_iteration - 1].relevant_ids) ) # Get the solutions from previous iteration .with_columns(pl.Series(cluster_column_name, clusters)) # Add clustering information from last iteration .filter(pl.col(cluster_column_name).is_in(winning_clusters)) # Keep only winning clusters .drop(cluster_column_name) # Drop cluster column ) relevant_ids = relevant_data[index_column_name].to_list() relevant_data = relevant_data.drop(index_column_name) # Drop index column return [ *state, SCOREBandsGDMResult( votes=votes, score_bands_result=score_json(relevant_data, config.score_bands_config), relevant_ids=relevant_ids, iteration=current_iteration, previous_iteration=config.from_iteration, ), ] ``` ### desdeo.mcdm.nimbus Functions related to the Sychronous NIMBUS method. References Miettinen, K., & Mäkelä, M. M. (2006). Synchronous approach in interactive multiobjective optimization. European Journal of Operational Research, 170(3), 909–922. #### NimbusError Bases: `Exception` Raised when an error with a NIMBUS method is encountered. Source code in `desdeo/mcdm/nimbus.py` ``` class NimbusError(Exception): """Raised when an error with a NIMBUS method is encountered.""" ``` #### generate_starting_point ``` generate_starting_point( problem: Problem, reference_point: dict[str, float] | None = None, scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> SolverResults ``` Generates a starting point for the NIMBUS method. Using the given reference point and achievement scalarizing function, finds one pareto optimal solution that can be used as a starting point for the NIMBUS method. If no reference point is given, ideal is used as the reference point. Instead of using this function, the user can provide a starting point. Raises: | Type | Description | | ------------- | ----------------------------------------------------------------- | | `NimbusError` | the given problem has an undefined ideal or nadir point, or both. | Parameters: | Name | Type | Description | Default | | ----------------------- | ------------------ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `reference_point` | \`dict[str, float] | None\` | an objective dictionary with a reference point. If not given, ideal will be used as reference point. | | `scalarization_options` | \`dict | None\` | optional kwargs passed to the scalarization function. Defaults to None. | | `solver` | \`BaseSolver | None\` | solver used to solve the problem. If not given, an appropriate solver will be automatically determined based on the features of problem. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Returns: | Type | Description | | --------------- | ------------------------------------------------------------------------------------------------------------ | | `SolverResults` | list\[SolverResults\]: a list of SolverResults objects. Contains as many elements as defined in num_desired. | Source code in `desdeo/mcdm/nimbus.py` ``` def generate_starting_point( problem: Problem, reference_point: dict[str, float] | None = None, scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> SolverResults: r"""Generates a starting point for the NIMBUS method. Using the given reference point and achievement scalarizing function, finds one pareto optimal solution that can be used as a starting point for the NIMBUS method. If no reference point is given, ideal is used as the reference point. Instead of using this function, the user can provide a starting point. Raises: NimbusError: the given problem has an undefined ideal or nadir point, or both. Args: problem (Problem): the problem being solved. reference_point (dict[str, float]|None): an objective dictionary with a reference point. If not given, ideal will be used as reference point. scalarization_options (dict | None, optional): optional kwargs passed to the scalarization function. Defaults to None. solver (BaseSolver | None, optional): solver used to solve the problem. If not given, an appropriate solver will be automatically determined based on the features of `problem`. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Returns: list[SolverResults]: a list of `SolverResults` objects. Contains as many elements as defined in `num_desired`. """ ideal = problem.get_ideal_point() nadir = problem.get_nadir_point() if None in ideal.values() or None in nadir.values(): msg = "The given problem must have both an ideal and nadir point defined." raise NimbusError(msg) _reference_point = dict(reference_point) if reference_point is not None else {} for obj in problem.objectives: if obj.symbol not in _reference_point: _reference_point[obj.symbol] = ideal[obj.symbol] init_solver = solver if solver is not None else guess_best_solver(problem) _solver_options = solver_options if solver_options is not None else None # solve ASF add_asf = add_asf_diff if problem.is_twice_differentiable else add_asf_nondiff problem_w_asf, asf_target = add_asf(problem, "asf", _reference_point, **(scalarization_options or {})) asf_solver = init_solver(problem_w_asf, _solver_options) if _solver_options else init_solver(problem_w_asf) return asf_solver.solve(asf_target) ``` #### infer_classifications ``` infer_classifications( problem: Problem, current_objectives: dict[str, float], reference_point: dict[str, float], ) -> dict[str, tuple[str, float | None]] ``` Infers NIMBUS classifications based on a reference point and current objective values. Infers the classifications based on a given reference point and current objective function values. The following classifications are inferred for each objective: - (I^{\<}): values that should improve, the reference point value of an objective function is equal to its ideal value; - (I^{\\leq}): values that should improve until a given aspiration level, the reference point value of an objective function is better than the current value; - (I^{=}): values that should stay as they are, the reference point value of an objective function is equal to the current value; - (I^{\\geq}): values that can be impaired until some reservation level, the reference point value of an objective function is worse than the current value; and - (I^{\\diamond}): values that are allowed to change freely, the reference point value of and objective function is equal to its nadir value. The aspiration levels and the reservation levels are then given for each classification, when relevant, in the return value of this function as the following example demonstrates: ``` classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Raises: | Type | Description | | ------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `NimbusError` | the ideal or nadir point, or both, of the given problem are undefined. | | `NimbusError` | the reference point or current objectives are missing entries for one or more of the objective functions defined in the problem. | Parameters: | Name | Type | Description | Default | | -------------------- | ------------------ | -------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the current objectives and the reference point are related to. | *required* | | `current_objectives` | `dict[str, float]` | an objective dictionary with the current objective functions values. | *required* | | `reference_point` | `dict[str, float]` | an objective dictionary with the reference point values. | *required* | Returns: | Type | Description | | ------------------------------ | ----------- | | \`dict\[str, tuple\[str, float | None\]\]\` | Source code in `desdeo/mcdm/nimbus.py` ```` def infer_classifications( problem: Problem, current_objectives: dict[str, float], reference_point: dict[str, float] ) -> dict[str, tuple[str, float | None]]: r"""Infers NIMBUS classifications based on a reference point and current objective values. Infers the classifications based on a given reference point and current objective function values. The following classifications are inferred for each objective: - $I^{<}$: values that should improve, the reference point value of an objective function is equal to its ideal value; - $I^{\leq}$: values that should improve until a given aspiration level, the reference point value of an objective function is better than the current value; - $I^{=}$: values that should stay as they are, the reference point value of an objective function is equal to the current value; - $I^{\geq}$: values that can be impaired until some reservation level, the reference point value of an objective function is worse than the current value; and - $I^{\diamond}$: values that are allowed to change freely, the reference point value of and objective function is equal to its nadir value. The aspiration levels and the reservation levels are then given for each classification, when relevant, in the return value of this function as the following example demonstrates: ```python classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Raises: NimbusError: the ideal or nadir point, or both, of the given problem are undefined. NimbusError: the reference point or current objectives are missing entries for one or more of the objective functions defined in the problem. Args: problem (Problem): the problem the current objectives and the reference point are related to. current_objectives (dict[str, float]): an objective dictionary with the current objective functions values. reference_point (dict[str, float]): an objective dictionary with the reference point values. Returns: dict[str, tuple[str, float | None]]: a dict with keys corresponding to the symbols of the objective functions defined for the problem and with values of tuples, where the first element is the classification (str) and the second element is either a reservation level (in case of classification `>=`) or an aspiration level (in case of classification `<=`). """ if None in problem.get_ideal_point().values() or None in problem.get_nadir_point().values(): msg = "The given problem must have both an ideal and nadir point defined." raise NimbusError(msg) if not all(obj.symbol in reference_point for obj in problem.objectives): msg = f"The reference point {reference_point} is missing entries for one or more of the objective functions." raise NimbusError(msg) if not all(obj.symbol in current_objectives for obj in problem.objectives): msg = f"The current point {current_objectives} is missing entries for one or more of the objective functions." raise NimbusError(msg) # derive the classifications based on the reference point and and previous # objective function values classifications = {} for obj in problem.objectives: if np.isclose(reference_point[obj.symbol], obj.nadir): # the objective is free to change classification = {obj.symbol: ("0", None)} elif np.isclose(reference_point[obj.symbol], obj.ideal): # the objective should improve classification = {obj.symbol: ("<", None)} elif np.isclose(reference_point[obj.symbol], current_objectives[obj.symbol]): # the objective should stay as it is classification = {obj.symbol: ("=", None)} elif not obj.maximize and reference_point[obj.symbol] < current_objectives[obj.symbol]: # minimizing objective, reference value smaller, this is an aspiration level # improve until classification = {obj.symbol: ("<=", reference_point[obj.symbol])} elif not obj.maximize and reference_point[obj.symbol] > current_objectives[obj.symbol]: # minimizing objective, reference value is greater, this is a reservations level # impair until classification = {obj.symbol: (">=", reference_point[obj.symbol])} elif obj.maximize and reference_point[obj.symbol] < current_objectives[obj.symbol]: # maximizing objective, reference value is smaller, this is a reservation level # impair until classification = {obj.symbol: (">=", reference_point[obj.symbol])} elif obj.maximize and reference_point[obj.symbol] > current_objectives[obj.symbol]: # maximizing objective, reference value is greater, this is an aspiration level # improve until classification = {obj.symbol: ("<=", reference_point[obj.symbol])} else: # could not figure classification msg = f"Warning: NIMBUS could not figure out the classification for objective {obj.symbol}." classifications |= classification return classifications ```` #### solve_intermediate_solutions ``` solve_intermediate_solutions( problem: Problem, solution_1: dict[str, VariableType], solution_2: dict[str, VariableType], num_desired: int, scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[SolverResults] ``` Generates a desired number of intermediate solutions between two given solutions. Generates a desires number of intermediate solutions given two Pareto optimal solutions. The solutions are generated by taking n number of steps between the two solutions in the objective space. The objective vectors corresponding to these solutions are then utilized as reference points in the achievement scalarizing function. Solving the functions for each reference point will project the reference point on the Pareto optimal front of the problem. These projected solutions are then returned. Note that the intermediate solutions are generated *between* the two given solutions, this means the returned solutions will not include the original points. Parameters: | Name | Type | Description | Default | | ----------------------- | ------------------------- | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `solution_1` | `dict[str, VariableType]` | the first of the solutions between which the intermediate solutions are to be generated. | *required* | | `solution_2` | `dict[str, VariableType]` | the second of the solutions between which the intermediate solutions are to be generated. | *required* | | `num_desired` | `int` | the number of desired intermediate solutions to be generated. Must be at least 1. | *required* | | `scalarization_options` | \`dict | None\` | optional kwargs passed to the scalarization function. Defaults to None. | | `solver` | \`BaseSolver | None\` | solver used to solve the problem. If not given, an appropriate solver will be automatically determined based on the features of problem. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Returns: | Type | Description | | --------------------- | ------------------------------------------------------------------------------------------------- | | `list[SolverResults]` | list\[SolverResults\]: a list with the projected intermediate solutions as SolverResults objects. | Source code in `desdeo/mcdm/nimbus.py` ``` def solve_intermediate_solutions( problem: Problem, solution_1: dict[str, VariableType], solution_2: dict[str, VariableType], num_desired: int, scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[SolverResults]: """Generates a desired number of intermediate solutions between two given solutions. Generates a desires number of intermediate solutions given two Pareto optimal solutions. The solutions are generated by taking n number of steps between the two solutions in the objective space. The objective vectors corresponding to these solutions are then utilized as reference points in the achievement scalarizing function. Solving the functions for each reference point will project the reference point on the Pareto optimal front of the problem. These projected solutions are then returned. Note that the intermediate solutions are generated _between_ the two given solutions, this means the returned solutions will not include the original points. Args: problem (Problem): the problem being solved. solution_1 (dict[str, VariableType]): the first of the solutions between which the intermediate solutions are to be generated. solution_2 (dict[str, VariableType]): the second of the solutions between which the intermediate solutions are to be generated. num_desired (int): the number of desired intermediate solutions to be generated. Must be at least `1`. scalarization_options (dict | None, optional): optional kwargs passed to the scalarization function. Defaults to None. solver (BaseSolver | None, optional): solver used to solve the problem. If not given, an appropriate solver will be automatically determined based on the features of `problem`. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Returns: list[SolverResults]: a list with the projected intermediate solutions as `SolverResults` objects. """ if int(num_desired) < 1: msg = f"The given number of desired intermediate ({num_desired=}) solutions must be at least 1." raise NimbusError(msg) init_solver = guess_best_solver(problem) if solver is None else solver _solver_options = None if solver_options is None or solver is None else solver_options # compute the element-wise difference between each solution (in the decision space) solution_1_arr = flatten_variable_dict(problem, solution_1) solution_2_arr = flatten_variable_dict(problem, solution_2) delta = solution_1_arr - solution_2_arr # the '2' is in the denominator because we want to calculate the steps # between the two given points; we are not interested in the given points themselves. step_size = delta / (2 + num_desired) intermediate_points = np.array([solution_2_arr + i * step_size for i in range(1, num_desired + 1)]) intermediate_var_values = pl.DataFrame( [unflatten_variable_array(problem, x) for x in intermediate_points], schema=[ (var.symbol, pl.Float64 if isinstance(var, Variable) else pl.Array(pl.Float64, tuple(var.shape))) for var in problem.variables ], ) # evaluate the intermediate points to get reference points # TODO(gialmisi): an evaluator might have to be selected depending on the problem evaluator = PolarsEvaluator(problem) reference_points = ( evaluator.evaluate(intermediate_var_values).select([obj.symbol for obj in problem.objectives]).to_dicts() ) # for each reference point, add and solve the ASF scalarization problem # projecting the reference point onto the Pareto optimal front of the problem. # TODO(gialmisi): this can be done in parallel. intermediate_solutions = [] for rp in reference_points: # add scalarization add_asf = add_asf_diff if problem.is_twice_differentiable else add_asf_nondiff asf_problem, target = add_asf(problem, "target", rp, **(scalarization_options or {})) solver_instance = init_solver(asf_problem, _solver_options) # solve and store results result: SolverResults = solver_instance.solve(target) intermediate_solutions.append(result) return intermediate_solutions ``` #### solve_sub_problems ``` solve_sub_problems( problem: Problem, current_objectives: dict[str, float], reference_point: dict[str, float], num_desired: int, scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[SolverResults] ``` Solves a desired number of sub-problems as defined in the NIMBUS methods. Solves 1-4 scalarized problems utilizing different scalarization functions. The scalarizations are based on the classification of a solutions provided by a decision maker. The classifications are represented by a reference point. Returns a number of new solutions corresponding to the number of scalarization functions solved. Depending on `num_desired`, solves the following scalarized problems corresponding the the following scalarization functions: 1. the NIMBUS scalarization function, 1. the STOM scalarization function, 1. the achievement scalarizing function, and 1. the GUESS scalarization function. Raises: | Type | Description | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `NimbusError` | the given problem has an undefined ideal or nadir point, or both. | | `NimbusError` | either the reference point of current objective functions value are missing entries for one or more of the objective functions defined in the problem. | Parameters: | Name | Type | Description | Default | | ----------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `current_objectives` | `dict[str, float]` | an objective dictionary with the objective functions values the classifications have been given with respect to. | *required* | | `reference_point` | `dict[str, float]` | an objective dictionary with a reference point. The classifications utilized in the sub problems are derived from the reference point. | *required* | | `num_desired` | `int` | the number of desired solutions to be solved. Solves as many scalarized problems. The value must be in the range 1-4. | *required* | | `scalarization_options` | \`dict | None\` | optional kwargs passed to the scalarization function. Defaults to None. | | `solver` | \`BaseSolver | None\` | solver used to solve the problem. If not given, an appropriate solver will be automatically determined based on the features of problem. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Returns: | Type | Description | | --------------------- | ------------------------------------------------------------------------------------------------------------ | | `list[SolverResults]` | list\[SolverResults\]: a list of SolverResults objects. Contains as many elements as defined in num_desired. | Source code in `desdeo/mcdm/nimbus.py` ``` def solve_sub_problems( problem: Problem, current_objectives: dict[str, float], reference_point: dict[str, float], num_desired: int, scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[SolverResults]: r"""Solves a desired number of sub-problems as defined in the NIMBUS methods. Solves 1-4 scalarized problems utilizing different scalarization functions. The scalarizations are based on the classification of a solutions provided by a decision maker. The classifications are represented by a reference point. Returns a number of new solutions corresponding to the number of scalarization functions solved. Depending on `num_desired`, solves the following scalarized problems corresponding the the following scalarization functions: 1. the NIMBUS scalarization function, 2. the STOM scalarization function, 3. the achievement scalarizing function, and 4. the GUESS scalarization function. Raises: NimbusError: the given problem has an undefined ideal or nadir point, or both. NimbusError: either the reference point of current objective functions value are missing entries for one or more of the objective functions defined in the problem. Args: problem (Problem): the problem being solved. current_objectives (dict[str, float]): an objective dictionary with the objective functions values the classifications have been given with respect to. reference_point (dict[str, float]): an objective dictionary with a reference point. The classifications utilized in the sub problems are derived from the reference point. num_desired (int): the number of desired solutions to be solved. Solves as many scalarized problems. The value must be in the range 1-4. scalarization_options (dict | None, optional): optional kwargs passed to the scalarization function. Defaults to None. solver (BaseSolver | None, optional): solver used to solve the problem. If not given, an appropriate solver will be automatically determined based on the features of `problem`. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Returns: list[SolverResults]: a list of `SolverResults` objects. Contains as many elements as defined in `num_desired`. """ if None in problem.get_ideal_point().values() or None in problem.get_nadir_point().values(): msg = "The given problem must have both an ideal and nadir point defined." raise NimbusError(msg) if not all(obj.symbol in reference_point for obj in problem.objectives): msg = f"The reference point {reference_point} is missing entries for one or more of the objective functions." raise NimbusError(msg) if not all(obj.symbol in current_objectives for obj in problem.objectives): msg = f"The current point {reference_point} is missing entries for one or more of the objective functions." raise NimbusError(msg) init_solver = solver if solver is not None else guess_best_solver(problem) _solver_options = solver_options if solver_options is not None else None # derive the classifications based on the reference point and and previous # objective function values classifications = infer_classifications(problem, current_objectives, reference_point) solutions = [] # solve the nimbus scalarization problem, this is done always add_nimbus_sf = add_nimbus_sf_diff if problem.is_twice_differentiable else add_nimbus_sf_nondiff problem_w_nimbus, nimbus_target = add_nimbus_sf( problem, "nimbus_sf", classifications, current_objectives, **(scalarization_options or {}) ) nimbus_solver = init_solver(problem_w_nimbus, _solver_options) if _solver_options else init_solver(problem_w_nimbus) solutions.append(nimbus_solver.solve(nimbus_target)) if num_desired > 1: # solve STOM add_stom_sf = add_stom_sf_diff if problem.is_twice_differentiable else add_stom_sf_nondiff problem_w_stom, stom_target = add_stom_sf(problem, "stom_sf", reference_point, **(scalarization_options or {})) stom_solver = init_solver(problem_w_stom, _solver_options) if _solver_options else init_solver(problem_w_stom) solutions.append(stom_solver.solve(stom_target)) if num_desired > 2: # noqa: PLR2004 # solve ASF add_asf = add_asf_diff if problem.is_twice_differentiable else add_asf_nondiff problem_w_asf, asf_target = add_asf(problem, "asf", reference_point, **(scalarization_options or {})) asf_solver = init_solver(problem_w_asf, _solver_options) if _solver_options else init_solver(problem_w_asf) solutions.append(asf_solver.solve(asf_target)) if num_desired > 3: # noqa: PLR2004 # solve GUESS add_guess_sf = add_guess_sf_diff if problem.is_twice_differentiable else add_guess_sf_nondiff problem_w_guess, guess_target = add_guess_sf( problem, "guess_sf", reference_point, **(scalarization_options or {}) ) if _solver_options: guess_solver = init_solver(problem_w_guess, _solver_options) else: guess_solver = init_solver(problem_w_guess) solutions.append(guess_solver.solve(guess_target)) return solutions ``` ### desdeo.mcdm.gnimbus Functions related to the GNIMBUS method. References: TBA #### GNIMBUSError Bases: `Exception` Raised when an error with a NIMBUS method is encountered. Source code in `desdeo/mcdm/gnimbus.py` ``` class GNIMBUSError(Exception): """Raised when an error with a NIMBUS method is encountered.""" ``` #### infer_group_classifications ``` infer_group_classifications( problem: Problem, current_objectives: dict[str, float], reference_points: dict[str, dict[str, float]], *, silent: bool = True, ) -> dict[ str, tuple[ Literal["improve", "worsen", "conflict"], list[float], ], ] ``` Infers group classification from the reference points given by the group. Parameters: | Name | Type | Description | Default | | -------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem being solved | *required* | | `current_objectives` | `dict[str, float]` | objective values at the current iteration | *required* | | `reference_points` | `dict[str, dict[str, float]]` | The reference points given by the group. The keys of the outer dict are the decision makers and the keys of the inner dict are objective symbols. | *required* | | `silent` | `bool` | If false, the classifications will be printed. | `True` | Raises: | Type | Description | | -------------- | ----------- | | `GNIMBUSError` | description | Returns: | Type | Description | | ------------------------------------------------------------------------- | --------------------------------------------------- | | `dict[str, tuple[Literal['improve', 'worsen', 'conflict'], list[float]]]` | dict\[str, tuple\[str, list[float]\]\]: description | Source code in `desdeo/mcdm/gnimbus.py` ``` def infer_group_classifications( problem: Problem, current_objectives: dict[str, float], reference_points: dict[str, dict[str, float]], *, silent: bool = True, ) -> dict[str, tuple[Literal["improve", "worsen", "conflict"], list[float]]]: """Infers group classification from the reference points given by the group. Args: problem (Problem): the problem being solved current_objectives (dict[str, float]): objective values at the current iteration reference_points (dict[str, dict[str, float]]): The reference points given by the group. The keys of the outer dict are the decision makers and the keys of the inner dict are objective symbols. silent (bool): If false, the classifications will be printed. Raises: GNIMBUSError: _description_ Returns: dict[str, tuple[str, list[float]]]: _description_ """ for dm, reference_point in reference_points.items(): # for rp in reference_point: if not all(obj.symbol in reference_point for obj in problem.objectives): print(reference_point) # noqa: T201 msg = ( f"The reference point {reference_point} of {dm} is missing entries " "for one or more of the objective functions." ) raise GNIMBUSError(msg) group_classifications = {} for obj in problem.objectives: # maximization if obj.maximize and all( ( reference_points[dm][obj.symbol] >= current_objectives[obj.symbol] or np.isclose(reference_points[dm][obj.symbol], current_objectives[obj.symbol]) ) for dm in reference_points ): classify = "improve" elif obj.maximize and all( reference_points[dm][obj.symbol] < current_objectives[obj.symbol] for dm in reference_points ): classify = "worsen" # minimization elif (not obj.maximize) and all( ( reference_points[dm][obj.symbol] <= current_objectives[obj.symbol] or np.isclose(reference_points[dm][obj.symbol], current_objectives[obj.symbol]) ) for dm in reference_points ): classify = "improve" elif (not obj.maximize) and all( reference_points[dm][obj.symbol] > current_objectives[obj.symbol] for dm in reference_points ): classify = "worsen" else: classify = "conflict" group_classifications[obj.symbol] = (classify, [reference_points[dm][obj.symbol] for dm in reference_points]) if not silent: for symbol, value in group_classifications.items(): if value[0] == "improve": print(f"The group wants to improve objective {symbol}") # noqa: T201 print(value[1]) # noqa: T201 if value[0] == "worsen": print(f"The group wants to worsen objective {symbol}") # noqa: T201 print(value[1]) # noqa: T201 if value[0] == "conflict": print(f"The group has conflicting views about objective {symbol}") # noqa: T201 print(value[1]) # noqa: T201 return group_classifications ``` #### solve_group_sub_problems ``` solve_group_sub_problems( problem: Problem, current_objectives: dict[str, float], reference_points: dict[str, dict[str, float]], phase: str, scalarization_options: dict | None = None, create_solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[SolverResults] ``` Solves a number of sub-problems as defined in the GNIMBUS methods. TODO: update docs Solves 4 scalarized problems utilizing different scalarization functions. The scalarizations are based on the classification of a solutions provided by a decision maker. The classifications are represented by a reference point. Returns a number of new solutions corresponding to the number of scalarization functions solved. Solves the following scalarized problems corresponding the the following scalarization functions: 1. the NIMBUS scalarization function, 1. the STOM scalarization function, 1. the achievement scalarizing function, and 1. the GUESS scalarization function. Raises: | Type | Description | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `GNIMBUSError` | the given problem has an undefined ideal or nadir point, or both. | | `GNIMBUSError` | either the reference point of current objective functions value are missing entries for one or more of the objective functions defined in the problem. | Parameters: | Name | Type | Description | Default | | ----------------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `current_objectives` | `dict[str, float]` | an objective dictionary with the objective functions values the classifications have been given with respect to. | *required* | | `reference_points` | `dict[str, dict[str, float]]` | A dictionary containing an objective dictionary with a reference point for each DM. The classifications utilized in the sub problems are derived from the reference points. | *required* | | `phase` | `str` | The selected phase of the solution process. Must be one of "learning", "crp", "decision" or "compromise". | *required* | | `scalarization_options` | \`dict | None\` | optional kwargs passed to the scalarization function. Defaults to None. | | `create_solver` | \`CreateSolverType | None\` | a function that given a problem, will return a solver. If not given, an appropriate solver will be automatically determined based on the features of problem. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the create_solver routine. Ignored if create_solver is None. Defaults to None. | Returns: | Type | Description | | --------------------- | ------------------------------------------------------------------------------------------------------------ | | `list[SolverResults]` | list\[SolverResults\]: a list of SolverResults objects. Contains as many elements as defined in num_desired. | Source code in `desdeo/mcdm/gnimbus.py` ``` def solve_group_sub_problems( # noqa: C901 problem: Problem, current_objectives: dict[str, float], reference_points: dict[str, dict[str, float]], phase: str, scalarization_options: dict | None = None, create_solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[SolverResults]: r"""Solves a number of sub-problems as defined in the GNIMBUS methods. TODO: update docs Solves 4 scalarized problems utilizing different scalarization functions. The scalarizations are based on the classification of a solutions provided by a decision maker. The classifications are represented by a reference point. Returns a number of new solutions corresponding to the number of scalarization functions solved. Solves the following scalarized problems corresponding the the following scalarization functions: 1. the NIMBUS scalarization function, 2. the STOM scalarization function, 3. the achievement scalarizing function, and 4. the GUESS scalarization function. Raises: GNIMBUSError: the given problem has an undefined ideal or nadir point, or both. GNIMBUSError: either the reference point of current objective functions value are missing entries for one or more of the objective functions defined in the problem. Args: problem(Problem): the problem being solved. current_objectives(dict[str, float]): an objective dictionary with the objective functions values the classifications have been given with respect to. reference_points(dict[str, dict[str, float]]): A dictionary containing an objective dictionary with a reference point for each DM. The classifications utilized in the sub problems are derived from the reference points. phase(str): The selected phase of the solution process. Must be one of "learning", "crp", "decision" or "compromise". scalarization_options(dict | None, optional): optional kwargs passed to the scalarization function. Defaults to None. create_solver(CreateSolverType | None, optional): a function that given a problem, will return a solver. If not given, an appropriate solver will be automatically determined based on the features of `problem`. Defaults to None. solver_options(SolverOptions | None, optional): optional options passed to the `create_solver` routine. Ignored if `create_solver` is `None`. Defaults to None. Returns: list[SolverResults]: a list of `SolverResults` objects. Contains as many elements as defined in `num_desired`. """ if None in problem.get_ideal_point() or None in problem.get_nadir_point(): msg = "The given problem must have both an ideal and nadir point defined." raise GNIMBUSError(msg) DMs = reference_points.keys() # noqa: N806 for dm in DMs: reference_point = reference_points[dm] # for rp in reference_point: if not all(obj.symbol in reference_point for obj in problem.objectives): print(reference_point) # noqa: T201 msg = ( f"The reference point {reference_point} is missing entries for one or more of the objective functions." ) raise GNIMBUSError(msg) # check that at least one objective function is allowed to be improved and one is allowed to worsen classifications = infer_classifications(problem, current_objectives, reference_point) if not any(classifications[obj.symbol][0] in ["<", "<="] for obj in problem.objectives) or not any( classifications[obj.symbol][0] in [">=", "0"] for obj in problem.objectives ): msg = ( f"The given classifications {classifications} should allow at least one objective function value " "to improve and one to worsen." ) raise GNIMBUSError(msg) if not all(obj.symbol in current_objectives for obj in problem.objectives): msg = f"The current point {current_objectives} is missing entries for one or more of the objective functions." raise GNIMBUSError(msg) init_solver = create_solver if create_solver is not None else guess_best_solver(problem) if init_solver is GurobipySolver and not solver_options: solver_options = {"OutputFlag": 0} # TODO: how does one want this to behave? _solver_options = solver_options if solver_options is not None else None # print("solver is ", init_solver) solutions = [] classification_list = [] achievable_prefs = [] ind_sols = [] reference_points_list = dict_of_rps_to_list_of_rps(reference_points) # Solve for individual solutions using nimbus scalarization. for dm_rp in reference_points: ind_sols.append( solve_sub_problems( problem=problem, current_objectives=current_objectives, reference_point=reference_points[dm_rp], num_desired=1, scalarization_options=None, solver=init_solver, solver_options=_solver_options, )[0], ) achievable_prefs = [] for q in range(len(reference_points)): achievable_prefs.append(ind_sols[q].optimal_objectives) agg_aspirations, agg_bounds = agg_aspbounds(achievable_prefs, problem) delta = scale_delta(problem, d=1e-6) if phase == "decision": for rp in reference_points.values(): classification_list.append(infer_classifications(problem, current_objectives, rp)) gnimbus_scala = add_group_nimbus_diff if problem.is_twice_differentiable else add_group_nimbus add_nimbus_sf = gnimbus_scala problem_g_nimbus, gnimbus_target = add_nimbus_sf( problem, "nimbus_sf", classification_list, current_objectives, agg_bounds, delta, **(scalarization_options or {}), ) if _solver_options: gnimbus_solver = init_solver(problem_g_nimbus, _solver_options) # type:ignore else: gnimbus_solver = init_solver(problem_g_nimbus) # type:ignore solutions.append(gnimbus_solver.solve(gnimbus_target)) infer_group_classifications(problem, current_objectives, reference_points, silent=False) return solutions if phase == "compromise": # Run compromise phase with applying group-asf. reference_points_list = dict_of_rps_to_list_of_rps(reference_points) # solve ASF add_asf = add_group_asf_diff if problem.is_twice_differentiable else add_group_asf problem_w_asf, asf_target = add_asf( problem, "asf", reference_points_list, agg_bounds, delta, **(scalarization_options or {}) ) if _solver_options: # noqa: SIM108 asf_solver = init_solver(problem_w_asf, _solver_options) # type:ignore else: asf_solver = init_solver(problem_w_asf) # type:ignore solutions.append(asf_solver.solve(asf_target)) return solutions """ classification_list = infer_group_classifications(problem, current_objectives, reference_points) # All cool, the preference's are in a bit of a different format that other branches but works. gnimbus_scala = add_group_nimbus_compromise_diff \ if problem.is_twice_differentiable else add_group_nimbus_compromise add_nimbus_sf = gnimbus_scala problem_g_nimbus, gnimbus_target = add_nimbus_sf( problem, "nimbus_sf", classification_list, current_objectives, **(scalarization_options or {}) ) # ISSUE: makes the problem not twice differentiable, thus the initial solver doesn't work # Also needed a little tweaking inside the scalarization functions. if _solver_options: gnimbus_solver = init_solver(problem_g_nimbus, _solver_options) # type:ignore else: gnimbus_solver = init_solver(problem_g_nimbus) # type:ignore solutions.append(gnimbus_solver.solve(gnimbus_target)) infer_group_classifications(problem, current_objectives, reference_points, silent=False) return solutions """ if phase == "learning": reference_points_list = dict_of_rps_to_list_of_rps(reference_points) # Add individual solutions for i in range(len(ind_sols)): solutions.append(ind_sols[i]) """ Group nimbus scalarization with delta and added hard_constraints """ classification_list = [] for rp in reference_points.values(): classification_list.append(infer_classifications(problem, current_objectives, rp)) print(classification_list) # noqa: T201 gnimbus_scala = add_group_nimbus_diff if problem.is_twice_differentiable else add_group_nimbus add_nimbus_sf = gnimbus_scala problem_w_nimbus, nimbus_target = add_nimbus_sf( problem, "nimbus_sf", classification_list, current_objectives, agg_bounds, delta, **(scalarization_options or {}), ) if _solver_options: nimbus_solver = init_solver(problem_w_nimbus, _solver_options) # type:ignore else: nimbus_solver = init_solver(problem_w_nimbus) # type:ignore solutions.append(nimbus_solver.solve(nimbus_target)) """ SOLVING Group Scals with scaled delta, original RPs and hard_constraints """ # solve STOM add_stom_sf = add_group_stom_diff if problem.is_twice_differentiable else add_group_stom problem_w_stom, stom_target = add_stom_sf( problem, "stom_sf", reference_points_list, agg_bounds, delta, **(scalarization_options or {}) ) if _solver_options: # noqa: SIM108 stom_solver = init_solver(problem_w_stom, _solver_options) # type:ignore else: stom_solver = init_solver(problem_w_stom) # type:ignore solutions.append(stom_solver.solve(stom_target)) # solve ASF add_asf = add_group_asf_diff if problem.is_twice_differentiable else add_group_asf problem_w_asf, asf_target = add_asf( problem, "asf", reference_points_list, agg_bounds, delta, **(scalarization_options or {}) ) if _solver_options: # noqa: SIM108 asf_solver = init_solver(problem_w_asf, _solver_options) # type:ignore else: asf_solver = init_solver(problem_w_asf) # type:ignore solutions.append(asf_solver.solve(asf_target)) # Solve GUESS add_guess_sf = add_group_guess_diff if problem.is_twice_differentiable else add_group_guess problem_w_guess, guess_target = add_guess_sf( problem, "guess_sf", reference_points_list, agg_bounds, delta, **(scalarization_options or {}) ) if _solver_options: guess_solver = init_solver(problem_w_guess, _solver_options) # type:ignore else: guess_solver = init_solver(problem_w_guess) # type:ignore solutions.append(guess_solver.solve(guess_target)) infer_group_classifications(problem, current_objectives, reference_points, silent=False) return solutions # phase is concsensus reaching # Add individual solutions for i in range(len(ind_sols)): solutions.append(ind_sols[i]) """ Group nimbus scalarization with delta and added hard_constraints """ classification_list = [] for rp in reference_points.values(): print("RPS", rp) # noqa: T201 classification_list.append(infer_classifications(problem, current_objectives, rp)) print(classification_list) # noqa: T201 gnimbus_scala = add_group_nimbus_diff if problem.is_twice_differentiable else add_group_nimbus add_nimbus_sf = gnimbus_scala problem_w_nimbus, nimbus_target = add_nimbus_sf( problem, "nimbus_sf", classification_list, current_objectives, agg_bounds, delta, **(scalarization_options or {}), ) if _solver_options: # noqa: SIM108 nimbus_solver = init_solver(problem_w_nimbus, _solver_options) # type:ignore else: nimbus_solver = init_solver(problem_w_nimbus) # type:ignore solutions.append(nimbus_solver.solve(nimbus_target)) """ SOLVING Group Scals with scaled delta, agg. aspirations and hard_constraints """ add_stom_sf2 = add_group_stom_agg_diff if problem.is_twice_differentiable else add_group_stom_agg problem_g_stom, stomg_target = add_stom_sf2( problem, "stom_sf2", agg_aspirations, agg_bounds, delta, **(scalarization_options or {}) ) if _solver_options: # noqa: SIM108 stomg_solver = init_solver(problem_g_stom, _solver_options) # type:ignore else: stomg_solver = init_solver(problem_g_stom) # type:ignore solutions.append(stomg_solver.solve(stomg_target)) add_asf2 = add_group_asf_agg_diff if problem.is_twice_differentiable else add_group_asf_agg problem_g_asf, asfg_target = add_asf2( problem, "asf2", agg_aspirations, agg_bounds, delta, **(scalarization_options or {}) ) if _solver_options: # noqa: SIM108 asfg_solver = init_solver(problem_g_asf, _solver_options) # type:ignore else: asfg_solver = init_solver(problem_g_asf) # type:ignore solutions.append(asfg_solver.solve(asfg_target)) add_guess_sf2 = add_group_guess_agg_diff if problem.is_twice_differentiable else add_group_guess_agg problem_g_guess, guess2_target = add_guess_sf2( problem, "guess_sf2", agg_aspirations, agg_bounds, delta, **(scalarization_options or {}) ) if _solver_options: # noqa: SIM108 guess2_solver = init_solver(problem_g_guess, _solver_options) # type:ignore else: guess2_solver = init_solver(problem_g_guess) # type:ignore solutions.append(guess2_solver.solve(guess2_target)) infer_group_classifications(problem, current_objectives, reference_points, silent=False) return solutions ``` #### voting_procedure ``` voting_procedure( problem: Problem, solutions, votes_idxs: dict[str, int] ) -> SolverResults ``` More general procedure for GNIMBUS for any number of DMs. TODO(@jpajasmaa): docs and cleaning up. Source code in `desdeo/mcdm/gnimbus.py` ``` def voting_procedure(problem: Problem, solutions, votes_idxs: dict[str, int]) -> SolverResults: """More general procedure for GNIMBUS for any number of DMs. TODO(@jpajasmaa): docs and cleaning up. """ # winner_idx = None # call majority """ general procedure does not apply majority rule winner_idx = majority_rule(votes_idxs) if winner_idx is not None: print("Majority winner", winner_idx) return solutions[winner_idx] """ # call plurality winners = plurality_rule(votes_idxs) print("winners") # noqa: T201 if len(winners) == 1: print("Plurality winner", winners[0]) # noqa: T201 return solutions[winners[0]] # need to unlist the winners list print("TIE-breaking, select a solution randomly among top voted ones") # noqa: T201 """ # if two same solutions with same number of votes, call intermediate # TODO:(@jpajasmaa) not perfect check as it is possible to have a problem that we can calculate more solutions # AND discrete representation also. if problem.discrete_representation is None: wsol1, wsol2 = solutions[winners[0]].optimal_variables, solutions[winners[1]].optimal_variables else: wsol1, wsol2 = solutions[winners[0]].optimal_objectives, solutions[winners[1]].optimal_objectives print("Finding intermediate solution between", wsol1, wsol2) # return solve_intermediate_solutions_only_objs(problem, wsol1, wsol2, num_desired=3) return solve_intermediate_solutions(problem, wsol1, wsol2, num_desired=1)[0] """ # n_of_sols = len(solutions) rng = np.random.default_rng() random_idx = rng.choice(winners) return solutions[random_idx] ``` ### desdeo.mcdm.enautilus Functions related to the E-NAUTILUS method are defined here. Reference of the method: Ruiz, A. B., Sindhya, K., Miettinen, K., Ruiz, F., & Luque, M. (2015). E-NAUTILUS: A decision support system for complex multiobjective optimization problems based on the NAUTILUS method. European Journal of Operational Research, 246(1), 218-231. #### ENautilusResult Bases: `BaseModel` The result of an iteration of the E-NAUTILUS method. Source code in `desdeo/mcdm/enautilus.py` ``` class ENautilusResult(BaseModel): """The result of an iteration of the E-NAUTILUS method.""" current_iteration: int = Field(description="Number of the current iteration.") iterations_left: int = Field(description="Number of iterations left.") intermediate_points: list[dict[str, float]] = Field(description="New intermediate points") reachable_best_bounds: list[dict[str, float]] = Field( description="Best bounds of the objective function values reachable from each intermediate point." ) reachable_worst_bounds: list[dict[str, float]] = Field( description="Worst bounds of the objective function values reachable from each intermediate point." ) closeness_measures: list[float] = Field(description="Closeness measures of each intermediate point.") reachable_point_indices: list[list[int]] = Field( description="Indices of the reachable points from each intermediate point." ) ``` #### calculate_closeness ``` calculate_closeness( z_intermediate: ndarray, z_nadir: ndarray, z_representative: ndarray, ) -> float ``` Calculate the closeness of an intermediate point to the non-dominated set. The greater the closeness is, the close intermediate point is to the non-dominated set. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | ---------------------------------------------- | ---------- | | `z_intermediate` | `ndarray` | the intermediate point. | *required* | | `z_nadir` | `ndarray` | the nadir point of the non-dominated set. | *required* | | `z_representative` | `ndarray` | the representative solution of z_intermediate. | *required* | Returns: | Name | Type | Description | | ------- | ------- | ---------------------- | | `float` | `float` | the closeness measure. | Source code in `desdeo/mcdm/enautilus.py` ``` def calculate_closeness(z_intermediate: np.ndarray, z_nadir: np.ndarray, z_representative: np.ndarray) -> float: """Calculate the closeness of an intermediate point to the non-dominated set. The greater the closeness is, the close intermediate point is to the non-dominated set. Args: z_intermediate (np.ndarray): the intermediate point. z_nadir (np.ndarray): the nadir point of the non-dominated set. z_representative (np.ndarray): the representative solution of `z_intermediate`. Returns: float: the closeness measure. """ return np.linalg.norm(z_intermediate - z_nadir) / np.linalg.norm(z_representative - z_nadir) * 100 ``` #### calculate_intermediate_points ``` calculate_intermediate_points( z_previous: ndarray, zs_representatives: ndarray, iterations_left: int, ) -> np.ndarray ``` Calculates the intermediate points to be shown to the decision maker at each iteration. The number of returned points depends on how many `zs_representative points` are supplied. Parameters: | Name | Type | Description | Default | | -------------------- | --------- | ------------------------------------------------------------------- | ---------- | | `z_previous` | `ndarray` | the point selected by the decision maker in the previous iteration. | *required* | | `zs_representatives` | `ndarray` | the representative solutions at the current iteration. | *required* | | `iterations_left` | `int` | the number of iterations left (including the current one). | *required* | Returns: | Type | Description | | --------- | -------------------------------------------- | | `ndarray` | np.ndarray: an array of intermediate points. | Source code in `desdeo/mcdm/enautilus.py` ``` def calculate_intermediate_points( z_previous: np.ndarray, zs_representatives: np.ndarray, iterations_left: int ) -> np.ndarray: """Calculates the intermediate points to be shown to the decision maker at each iteration. The number of returned points depends on how many `zs_representative points` are supplied. Args: z_previous (np.ndarray): the point selected by the decision maker in the previous iteration. zs_representatives (np.ndarray): the representative solutions at the current iteration. iterations_left (int): the number of iterations left (including the current one). Returns: np.ndarray: an array of intermediate points. """ return ((iterations_left - 1) / iterations_left) * z_previous + (1 / iterations_left) * zs_representatives ``` #### calculate_lower_bounds ``` calculate_lower_bounds( non_dominated_points: ndarray, z_intermediate: ndarray ) -> np.ndarray ``` Calculates the lower bounds of reachable solutions from an intermediate point. The lower bounds are calculated by solving an epsilon-constraint problem with the epsilon values taken from the intermediate point. Parameters: | Name | Type | Description | Default | | ---------------------- | --------- | ----------------------------------------------------------------------------------- | ---------- | | `non_dominated_points` | `ndarray` | a set of non-dominated points according to which the reachable values are computed. | *required* | | `z_intermediate` | `ndarray` | the intermediate point according to which the lower bounds are calculated. | *required* | Returns: | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: the lower bounds of reachable solutions on the non-dominated set based from the intermediate point. | Source code in `desdeo/mcdm/enautilus.py` ``` def calculate_lower_bounds(non_dominated_points: np.ndarray, z_intermediate: np.ndarray) -> np.ndarray: """Calculates the lower bounds of reachable solutions from an intermediate point. The lower bounds are calculated by solving an epsilon-constraint problem with the epsilon values taken from the intermediate point. Args: non_dominated_points (np.ndarray): a set of non-dominated points according to which the reachable values are computed. z_intermediate (np.ndarray): the intermediate point according to which the lower bounds are calculated. Returns: np.ndarray: the lower bounds of reachable solutions on the non-dominated set based from the intermediate point. """ k = non_dominated_points.shape[1] bounds = [] for r in range(k): # Indices of objectives other than r other = np.delete(np.arange(k), r) # Find points that are no worse than z_intermediate in all objectives except r mask = np.all(non_dominated_points[:, other] <= z_intermediate[other], axis=1) feasible = non_dominated_points[mask] if feasible.size > 0: bounds.append(np.min(feasible[:, r])) else: bounds.append(np.inf) # No feasible point in this projection return np.array(bounds) ``` #### calculate_reachable_subset ``` calculate_reachable_subset( non_dominated_points: ndarray, reachable_indices: ndarray, lower_bounds: ndarray, z_preferred: ndarray, ) -> list[int] ``` Calculates the reachable subset on a non-dominated set from a selected intermediate point. Parameters: | Name | Type | Description | Default | | ---------------------- | --------- | --------------------------------------------------------------------------------------- | ---------- | | `non_dominated_points` | `ndarray` | the original set of non-dominated points. | *required* | | `reachable_indices` | `ndarray` | the currently reachable indices, which will be used to select the new reachable points. | *required* | | `lower_bounds` | `ndarray` | the lower bounds of the reachable subset of non-dominates points. | *required* | | `z_preferred` | `ndarray` | the selected intermediate point subject to the reachable subset is calculated. | *required* | Returns: | Type | Description | | ----------- | --------------------------------------------------- | | `list[int]` | list\[int\]: the indices of the reachable solutions | Source code in `desdeo/mcdm/enautilus.py` ``` def calculate_reachable_subset( non_dominated_points: np.ndarray, reachable_indices: np.ndarray, lower_bounds: np.ndarray, z_preferred: np.ndarray ) -> list[int]: """Calculates the reachable subset on a non-dominated set from a selected intermediate point. Args: non_dominated_points (np.ndarray): the original set of non-dominated points. reachable_indices (np.ndarray): the currently reachable indices, which will be used to select the new reachable points. lower_bounds (np.ndarray): the lower bounds of the reachable subset of non-dominates points. z_preferred (np.ndarray): the selected intermediate point subject to the reachable subset is calculated. Returns: list[int]: the indices of the reachable solutions """ return [ i for i, z in enumerate(non_dominated_points) if np.all(lower_bounds <= z) and np.all(z <= z_preferred) and i in reachable_indices ] ``` #### enautilus_get_representative_solutions ``` enautilus_get_representative_solutions( problem: Problem, result: ENautilusResult, non_dominated_points: DataFrame, ) -> list[SolverResults] ``` Returns the solution corresponding to the intermediate points. The representative points are selected based on the current intermediate points. If the number of iterations left is 0, then the intermediate and representative points are equal. Parameters: | Name | Type | Description | Default | | ---------------------- | ----------------- | -------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem being solved. | *required* | | `result` | `ENautilusResult` | an ENautilusResponse returned by enautilus_step. | *required* | | `non_dominated_points` | `DataFrame` | a dataframe from which the representative solutions are taken. | *required* | Returns: | Name | Type | Description | | --------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `SolverResults` | `list[SolverResults]` | full information about the solutions. If information other than just objective function values are expected, then the supplied non_dominated_points should contain this information. | Source code in `desdeo/mcdm/enautilus.py` ``` def enautilus_get_representative_solutions( problem: Problem, result: ENautilusResult, non_dominated_points: pl.DataFrame ) -> list[SolverResults]: """Returns the solution corresponding to the intermediate points. The representative points are selected based on the current intermediate points. If the number of iterations left is 0, then the intermediate and representative points are equal. Args: problem (Problem): the problem being solved. result (ENautilusResult): an ENautilusResponse returned by `enautilus_step`. non_dominated_points (pl.DataFrame): a dataframe from which the representative solutions are taken. Returns: SolverResults: full information about the solutions. If information other than just objective function values are expected, then the supplied `non_dominated_points` should contain this information. """ obj_syms = [obj.symbol for obj in problem.objectives] const_syms = [con.symbol for con in problem.constraints] if problem.constraints else None extra_syms = [extra.symbol for extra in problem.extra_funcs] if problem.extra_funcs else None scal_syms = [scal.symbol for scal in problem.scalarization_funcs] if problem.scalarization_funcs else None # Build the list of variable column names present in the DataFrame. # Scalar variables use their symbol directly; tensor variables are unrolled # into columns like "sv_1", "sv_2", ... matching the convention used by # solve_epsilon.py and the representative solution set upload. available_cols = set(non_dominated_points.columns) var_col_names: list[str] = [] for var in problem.variables: if isinstance(var, TensorVariable): # Collect unrolled columns: symbol_1, symbol_2, ... n_elements = 1 for d in var.shape: n_elements *= d for i in range(1, n_elements + 1): col = f"{var.symbol}_{i}" if col in available_cols: var_col_names.append(col) elif var.symbol in available_cols: var_col_names.append(var.symbol) # Objective matrix (rows = ND points, cols = objectives, original senses) obj_matrix = non_dominated_points.select(obj_syms).to_numpy() solver_results: list[SolverResults] = [] for interm in result.intermediate_points: interm_vec = np.array([interm[sym] for sym in obj_syms], dtype=float) # Find index of closest ND point (Euclidean distance) idx = int(np.argmin(np.linalg.norm(obj_matrix - interm_vec, axis=1))) row = non_dominated_points[idx] var_dict = {col: row[col] for col in var_col_names} obj_dict = {sym: row[sym] for sym in obj_syms} const_dict = {sym: row[sym] for sym in const_syms if sym in row} if const_syms is not None else None extra_dict = {sym: row[sym] for sym in extra_syms if sym in row} if extra_syms is not None else None scal_dict = {sym: row[sym] for sym in scal_syms if sym in row} if scal_syms is not None else None solver_results.append( SolverResults( optimal_variables=var_dict, optimal_objectives=obj_dict, constraint_values=const_dict, extra_func_values=extra_dict, scalarization_values=scal_dict, success=True, message="E-NAUTILUS: nearest non-dominated point selected for intermediate point.", ) ) return solver_results ``` #### enautilus_step ``` enautilus_step( problem: Problem, non_dominated_points: DataFrame | dict[str, float], current_iteration: int, iterations_left: int, selected_point: dict[str, float], reachable_point_indices: list[int], number_of_intermediate_points: int, ) -> ENautilusResult ``` Compute one iteration of the E-NAUTILUS method. It is assumed that information from a previous iteration (selected point, etc.) is available either from a previous iteration of E-NAUTILUS, or if this is the first iteration, then the selected (intermediate) point `selected_point` should be the approximated nadir point from `non_dominated_points`. In this case, the `reachable_point_indices` should cover the whole of `non_dominated_points`. After the first iteration, all the information for computing the next iteration is always available from the previous iteration's result of this function (plus the `selected_point` provided by e.g., a decision maker). Parameters: | Name | Type | Description | Default | | ------------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem being solved. Used mainly for manipulating the other arguments. | *required* | | `non_dominated_points` | `DataFrame` | a set of non-dominated points approximating the Pareto front of Problem. This should be a Polars dataframe with at least columns that match the objective function symbols in Problem and the corresponding minimization value column. I.e., for an objective with symbol 'f1' the dataframe should have the symbols 'f1' and 'f1_min', where the column 'f1_min has the corresponding values of 'f1', but assuming minimization (N.B. if 'f1' is minimized, then 'f1_min' would have identical values as 'f1'). If provided as a dict, this will be converted to a polars dataframe. | *required* | | `current_iteration` | `int` | the number of the current iteration. For the first iteration, this should be zero. | *required* | | `iterations_left` | `int` | how many iteration are left (counting the current one). | *required* | | `selected_point` | `dict[str, float]` | the selected intermediate point in the previous iteration. If this is the first iteration, then this should be the nadir point approximated from non_dominated_points. | *required* | | `reachable_point_indices` | `list[int]` | the indices of the points in non_dominated_points that are reachable from current_iteration_point. | *required* | | `number_of_intermediate_points` | `int` | how many intermediate points are generated. | *required* | Returns: | Name | Type | Description | | ----------------- | ----------------- | ---------------------------- | | `ENautilusResult` | `ENautilusResult` | the result of the iteration. | Source code in `desdeo/mcdm/enautilus.py` ``` def enautilus_step( problem: Problem, non_dominated_points: pl.DataFrame | dict[str, float], current_iteration: int, iterations_left: int, selected_point: dict[str, float], reachable_point_indices: list[int], number_of_intermediate_points: int, ) -> ENautilusResult: """Compute one iteration of the E-NAUTILUS method. It is assumed that information from a previous iteration (selected point, etc.) is available either from a previous iteration of E-NAUTILUS, or if this is the first iteration, then the selected (intermediate) point `selected_point` should be the approximated nadir point from `non_dominated_points`. In this case, the `reachable_point_indices` should cover the whole of `non_dominated_points`. After the first iteration, all the information for computing the next iteration is always available from the previous iteration's result of this function (plus the `selected_point` provided by e.g., a decision maker). Args: problem (Problem): the problem being solved. Used mainly for manipulating the other arguments. non_dominated_points (pl.DataFrame): a set of non-dominated points approximating the Pareto front of `Problem`. This should be a Polars dataframe with at least columns that match the objective function symbols in `Problem` and the corresponding minimization value column. I.e., for an objective with symbol 'f1' the dataframe should have the symbols 'f1' and 'f1_min', where the column 'f1_min has the corresponding values of 'f1', but assuming minimization (N.B. if 'f1' is minimized, then 'f1_min' would have identical values as 'f1'). If provided as a `dict`, this will be converted to a polars dataframe. current_iteration (int): the number of the current iteration. For the first iteration, this should be zero. iterations_left (int): how many iteration are left (counting the current one). selected_point (dict[str, float]): the selected intermediate point in the previous iteration. If this is the first iteration, then this should be the nadir point approximated from `non_dominated_points`. reachable_point_indices (list[int]): the indices of the points in `non_dominated_points` that are reachable from `current_iteration_point`. number_of_intermediate_points (int): how many intermediate points are generated. Returns: ENautilusResult: the result of the iteration. """ # treat everything as minimized # selected point as numpy array, correct for minimization z_h = objective_dict_to_numpy_array(problem, flip_maximized_objective_values(problem, selected_point)) # subset of reachable solutions, take _min column if isinstance(non_dominated_points, dict): # dict converted to Polars dataframe _non_dominated_points = pl.DataFrame(non_dominated_points) else: # already Polars dataframe _non_dominated_points = non_dominated_points non_dom_objectives = _non_dominated_points[[f"{obj.symbol}_min" for obj in problem.objectives]].to_numpy() p_h = non_dom_objectives[reachable_point_indices] # estimate nadir from non-dominated points, treating as minimized problem z_nadir = non_dom_objectives.max(axis=0) # compute representative points representative_points = prune_by_average_linkage(p_h, number_of_intermediate_points) # calculate intermediate points intermediate_points = calculate_intermediate_points(z_h, representative_points, iterations_left) # calculate lower bounds intermediate_lower_bounds = [ calculate_lower_bounds(p_h, intermediate_point) for intermediate_point in intermediate_points ] # calculate closeness measures closeness_measures = [ calculate_closeness(intermediate_point, z_nadir, representative_point) for (intermediate_point, representative_point) in zip(intermediate_points, representative_points, strict=True) ] # calculate the indices of the reachable points for each intermediate point reachable_from_intermediate = [ calculate_reachable_subset(non_dom_objectives, reachable_point_indices, lower_bounds, interm) for lower_bounds, interm in zip(intermediate_lower_bounds, intermediate_points, strict=True) ] best_bounds = [ flip_maximized_objective_values(problem, numpy_array_to_objective_dict(problem, bounds)) for bounds in intermediate_lower_bounds ] worst_bounds = [ flip_maximized_objective_values(problem, numpy_array_to_objective_dict(problem, point)) for point in intermediate_points ] corrected_intermediate_points = [ flip_maximized_objective_values(problem, numpy_array_to_objective_dict(problem, point)) for point in intermediate_points ] return ENautilusResult( current_iteration=current_iteration + 1, iterations_left=iterations_left - 1, intermediate_points=corrected_intermediate_points, reachable_best_bounds=best_bounds, reachable_worst_bounds=worst_bounds, closeness_measures=closeness_measures, reachable_point_indices=reachable_from_intermediate, ) ``` #### prune_by_average_linkage ``` prune_by_average_linkage( non_dominated_points: ndarray, k: int ) -> np.ndarray ``` Prune a set of non-dominated points using average linkage clustering (Morse, 1980). This is used to calculate the representative solutions in E-NAUTILUS. Parameters: | Name | Type | Description | Default | | ---------------------- | --------- | ---------------------------------------------------- | ---------- | | `non_dominated_points` | `ndarray` | an array of non-dominated points in objective space. | *required* | | `k` | `int` | Number of representative points to retain. | *required* | Returns: | Type | Description | | --------- | ---------------------------------------------- | | `ndarray` | np.ndarray: an array of representative points. | Source code in `desdeo/mcdm/enautilus.py` ``` def prune_by_average_linkage(non_dominated_points: np.ndarray, k: int) -> np.ndarray: """Prune a set of non-dominated points using average linkage clustering (Morse, 1980). This is used to calculate the representative solutions in E-NAUTILUS. Args: non_dominated_points (np.ndarray): an array of non-dominated points in objective space. k (int): Number of representative points to retain. Returns: np.ndarray: an array of representative points. """ if len(non_dominated_points) <= k: # no need to prune return non_dominated_points # Compute pairwise distances distances = pdist(non_dominated_points, metric="euclidean") # Hierarchical clustering using average linkage z = linkage(distances, method="average") # Cut tree to form k clusters cluster_labels = fcluster(z, k, criterion="maxclust") # For each cluster, choose the point closest to the centroid representatives = [] for cluster_id in range(1, k + 1): cluster_points = non_dominated_points[cluster_labels == cluster_id] centroid = cluster_points.mean(axis=0) closest_idx = np.argmin(np.linalg.norm(cluster_points - centroid, axis=1)) representatives.append(cluster_points[closest_idx]) return np.array(representatives) ``` ### desdeo.mcdm.nautili Methods for the NAUTILI (a group decision making variant for NAUTILUS) method. #### NAUTILI_Response Bases: `BaseModel` The response of the NAUTILI method. Source code in `desdeo/mcdm/nautili.py` ``` class NAUTILI_Response(BaseModel): # noqa: N801 """The response of the NAUTILI method.""" step_number: int = Field(description="The step number associted with this response.") distance_to_front: float = Field( description=( "The distance travelled to the Pareto front. " "The distance is a ratio of the distances between the nadir and navigation point, and " "the nadir and the reachable objective vector. The distance is given in percentage." ) ) reference_points: dict | None = Field(description="The reference points used in the step.") improvement_directions: dict | None = Field(description="The improvement directions for each DM.") group_improvement_direction: dict | None = Field(description="The group improvement direction.") navigation_point: dict = Field(description="The navigation point used in the step.") reachable_solution: dict | None = Field(description="The reachable solution found in the step.") reachable_bounds: dict = Field(description="The reachable bounds found in the step.") ``` #### NautiliError Bases: `Exception` Exception raised for errors in the NAUTILI method. Source code in `desdeo/mcdm/nautili.py` ``` class NautiliError(Exception): """Exception raised for errors in the NAUTILI method.""" ``` #### nautili_all_steps ``` nautili_all_steps( problem: Problem, steps_remaining: int, reference_points: dict[str, dict[str, float]], previous_responses: list[NAUTILI_Response], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> [NAUTILI_Response] ``` Run all remaining NAUTILI steps for the given reference points and return the responses. Source code in `desdeo/mcdm/nautili.py` ``` def nautili_all_steps( problem: Problem, steps_remaining: int, reference_points: dict[str, dict[str, float]], previous_responses: list[NAUTILI_Response], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> [NAUTILI_Response]: """Run all remaining NAUTILI steps for the given reference points and return the responses.""" responses = [] nav_point = previous_responses[-1].navigation_point step_number = previous_responses[-1].step_number + 1 first_iteration = True reachable_solution = dict # Calculate the improvement directions for each DM improvement_directions = {} for dm in reference_points: # noqa: PLC0206 if reference_points[dm] is None: # If no reference point is provided, use the previous improvement direction if previous_responses[-1].reference_points is None: raise NautiliError("A reference point must be provided for the first iteration.") if previous_responses[-1].improvement_directions is None: raise NautiliError("An improvement direction must be provided for the first iteration.") reference_points[dm] = previous_responses[-1].reference_points[dm] improvement_directions[dm] = previous_responses[-1].improvement_directions[dm] else: # If a reference point is provided, calculate the improvement direction # First, check if the reference point is better than the navigation point max_multiplier = [-1 if obj.maximize else 1 for obj in problem.objectives] reference_point = ( np.array([reference_points[dm][obj.symbol] for obj in problem.objectives]) * max_multiplier ) nav_point_arr = np.array([nav_point[obj.symbol] for obj in problem.objectives]) * max_multiplier improvement = nav_point_arr - reference_point if np.any(improvement < 0): msg = ( f"If a reference point is provided, it must be better than the navigation point.\n" f" The reference point for {dm} is not better than the navigation point.\n" f" Reference point: {reference_point}, Navigation point: {nav_point}\n" f"Check objectives {np.where(improvement < 0)}" ) raise NautiliError(msg) # The improvement direction is in the true objective space improvement_directions[dm] = improvement * max_multiplier mean_improvement_direction = np.mean(list(improvement_directions.values()), axis=0) group_improvement_direction = { obj.symbol: mean_improvement_direction[i] for i, obj in enumerate(problem.objectives) } while steps_remaining > 0: if first_iteration: response = nautili_step( problem, steps_remaining=steps_remaining, step_number=step_number, nav_point=nav_point, group_improvement_direction=group_improvement_direction, solver=solver, solver_options=solver_options, ) first_iteration = False else: response = nautili_step( problem, steps_remaining=steps_remaining, step_number=step_number, nav_point=nav_point, reachable_solution=reachable_solution, solver=solver, solver_options=solver_options, ) response.reference_points = reference_points response.improvement_directions = improvement_directions responses.append(response) reachable_solution = response.reachable_solution nav_point = response.navigation_point steps_remaining -= 1 step_number += 1 return responses ``` #### nautili_init ``` nautili_init( problem: Problem, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> NAUTILI_Response ``` Initializes the NAUTILI method. Creates the initial response of the method, which sets the navigation point to the nadir point and the reachable bounds to the ideal and nadir points. Parameters: | Name | Type | Description | Default | | ---------------- | --------------- | ------------------------- | ----------------------------------------------------------------------------------- | | `problem` | `Problem` | The problem to be solved. | *required* | | `solver` | \`BaseSolver | None\` | The solver to use. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Returns: | Name | Type | Description | | ------------------- | ------------------ | ----------------------------------- | | `NAUTILUS_Response` | `NAUTILI_Response` | The initial response of the method. | Source code in `desdeo/mcdm/nautili.py` ``` def nautili_init( problem: Problem, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None ) -> NAUTILI_Response: """Initializes the NAUTILI method. Creates the initial response of the method, which sets the navigation point to the nadir point and the reachable bounds to the ideal and nadir points. Args: problem (Problem): The problem to be solved. solver (BaseSolver | None, optional): The solver to use. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Returns: NAUTILUS_Response: The initial response of the method. """ nav_point = get_nadir_dict(problem) lower_bounds, upper_bounds = solve_reachable_bounds( problem, nav_point, solver=solver, solver_options=solver_options ) return NAUTILI_Response( distance_to_front=0, navigation_point=nav_point, reachable_bounds={"lower_bounds": lower_bounds, "upper_bounds": upper_bounds}, reachable_solution=None, reference_points=None, improvement_directions=None, group_improvement_direction=None, step_number=0, ) ``` #### nautili_step ``` nautili_step( problem: Problem, steps_remaining: int, step_number: int, nav_point: dict, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, group_improvement_direction: dict | None = None, reachable_solution: dict | None = None, ) -> NAUTILI_Response ``` Perform a single step of the NAUTILI method. Source code in `desdeo/mcdm/nautili.py` ``` def nautili_step( problem: Problem, steps_remaining: int, step_number: int, nav_point: dict, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, group_improvement_direction: dict | None = None, reachable_solution: dict | None = None, ) -> NAUTILI_Response: """Perform a single step of the NAUTILI method.""" if group_improvement_direction is None and reachable_solution is None: raise NautiliError("Either group_improvement_direction or reachable_solution must be provided.") if group_improvement_direction is not None and reachable_solution is not None: raise NautiliError("Only one of group_improvement_direction or reachable_solution should be provided.") if group_improvement_direction is not None: opt_result = solve_reachable_solution( problem, group_improvement_direction, nav_point, solver, solver_options=solver_options ) reachable_solution = opt_result.optimal_objectives # update nav point new_nav_point = calculate_navigation_point(problem, nav_point, reachable_solution, steps_remaining) # update_bounds lower_bounds, upper_bounds = solve_reachable_bounds( problem, new_nav_point, solver=solver, solver_options=solver_options ) distance = calculate_distance_to_front(problem, new_nav_point, reachable_solution) return NAUTILI_Response( step_number=step_number, distance_to_front=distance, reference_points=None, improvement_directions=None, group_improvement_direction=group_improvement_direction, navigation_point=new_nav_point, reachable_solution=reachable_solution, reachable_bounds={"lower_bounds": lower_bounds, "upper_bounds": upper_bounds}, ) ``` #### solve_reachable_bounds ``` solve_reachable_bounds( problem: Problem, navigation_point: dict[str, float], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> tuple[dict[str, float], dict[str, float]] ``` Computes the current reachable (upper and lower) bounds of the solutions in the objective space. The reachable bound are computed based on the current navigation point. The bounds are computed by solving an epsilon constraint problem. Parameters: | Name | Type | Description | Default | | ------------------ | ------------------ | -------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `navigation_point` | `dict[str, float]` | the navigation point limiting the reachable area. The key is the objective function's symbol and the value the navigation point. | *required* | | `solver` | \`BaseSolver | None\` | solver based on BaseSolver used to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Raises: | Type | Description | | -------------- | --------------------------------------------------------------------- | | `NautiliError` | when optimization of an epsilon constraint problem is not successful. | Returns: | Type | Description | | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `tuple[dict[str, float], dict[str, float]]` | tuple\[dict[str, float], dict[str, float]\]: a tuple of dicts, where the first dict are the lower bounds and the second element the upper bounds, the key is the symbol of each objective. | Source code in `desdeo/mcdm/nautili.py` ``` def solve_reachable_bounds( problem: Problem, navigation_point: dict[str, float], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> tuple[dict[str, float], dict[str, float]]: """Computes the current reachable (upper and lower) bounds of the solutions in the objective space. The reachable bound are computed based on the current navigation point. The bounds are computed by solving an epsilon constraint problem. Args: problem (Problem): the problem being solved. navigation_point (dict[str, float]): the navigation point limiting the reachable area. The key is the objective function's symbol and the value the navigation point. solver (BaseSolver | None, optional): solver based on BaseSolver used to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Raises: NautiliError: when optimization of an epsilon constraint problem is not successful. Returns: tuple[dict[str, float], dict[str, float]]: a tuple of dicts, where the first dict are the lower bounds and the second element the upper bounds, the key is the symbol of each objective. """ # If an objective is to be maximized, then the navigation point component of that objective should be # multiplied by -1. const_bounds = { objective.symbol: -1 * navigation_point[objective.symbol] if objective.maximize else navigation_point[objective.symbol] for objective in problem.objectives } # if a solver creator was provided, use that, else, guess the best one solver_init = guess_best_solver(problem) if solver is None else solver _solver_options = None if solver_options is None or solver is None else solver_options lower_bounds = {} upper_bounds = {} for objective in problem.objectives: # Lower bounds eps_problem, target, _ = add_epsilon_constraints( problem, "target", {f"{obj.symbol}": f"{obj.symbol}_eps" for obj in problem.objectives}, objective.symbol, const_bounds, ) # solve solver_instance = solver_init(eps_problem, _solver_options) res = solver_instance.solve(target) if not res.success: # could not optimize eps problem msg = ( f"Optimizing the epsilon constrait problem for the objective " f"{objective.symbol} was not successful. Reason: {res.message}" ) raise NautiliError(msg) lower_bound = res.optimal_objectives[objective.symbol] if isinstance(lower_bound, list): lower_bound = lower_bound[0] # solver upper bounds # the lower bounds is set as in the NAUTILUS method, e.g., taken from # the current iteration/navigation point if isinstance(navigation_point[objective.symbol], list): # It should never be a list accordint to the type hints upper_bound = navigation_point[objective.symbol][0] else: upper_bound = navigation_point[objective.symbol] # add the lower and upper bounds logically depending whether an objective is to be maximized or minimized lower_bounds[objective.symbol] = lower_bound if not objective.maximize else upper_bound upper_bounds[objective.symbol] = upper_bound if not objective.maximize else lower_bound return lower_bounds, upper_bounds ``` #### solve_reachable_solution ``` solve_reachable_solution( problem: Problem, group_improvement_direction: dict[str, float], previous_nav_point: dict[str, float], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> SolverResults ``` Calculates the reachable solution on the Pareto optimal front. For the calculation to make sense in the context of NAUTILI, the reference point should be bounded by the reachable bounds present at the navigation step the reference point has been given. In practice, the reachable solution is calculated by solving an achievement scalarizing function. Parameters: | Name | Type | Description | Default | | ----------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `group_improvement_direction` | `dict[str, float]` | the improvement direction for the group. | *required* | | `previous_nav_point` | `dict[str, float]` | the previous navigation point. The reachable solution found is always better than the previous navigation point. | *required* | | `solver` | \`BaseSolver | None\` | solver based on BaseSolver used to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Returns: | Name | Type | Description | | --------------- | --------------- | ------------------------------ | | `SolverResults` | `SolverResults` | the results of the projection. | Source code in `desdeo/mcdm/nautili.py` ``` def solve_reachable_solution( problem: Problem, group_improvement_direction: dict[str, float], previous_nav_point: dict[str, float], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> SolverResults: """Calculates the reachable solution on the Pareto optimal front. For the calculation to make sense in the context of NAUTILI, the reference point should be bounded by the reachable bounds present at the navigation step the reference point has been given. In practice, the reachable solution is calculated by solving an achievement scalarizing function. Args: problem (Problem): the problem being solved. group_improvement_direction (dict[str, float]): the improvement direction for the group. previous_nav_point (dict[str, float]): the previous navigation point. The reachable solution found is always better than the previous navigation point. solver (BaseSolver | None, optional): solver based on BaseSolver used to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Returns: SolverResults: the results of the projection. """ # check solver init_solver = guess_best_solver(problem) if solver is None else solver _solver_options = None if solver_options is None or solver is None else solver_options # create and add scalarization function # previous_nav_point = objective_dict_to_numpy_array(problem, previous_nav_point).tolist() # weights = objective_dict_to_numpy_array(problem, group_improvement_direction).tolist() if problem.is_twice_differentiable: problem_w_asf, target = add_asf_generic_diff( problem, symbol="asf", reference_point=previous_nav_point, weights=group_improvement_direction, reference_point_aug=previous_nav_point, ) else: problem_w_asf, target = add_asf_generic_nondiff( problem, symbol="asf", reference_point=previous_nav_point, weights=group_improvement_direction, reference_point_aug=previous_nav_point, ) # Note: We do not solve the global problem. Instead, we solve this constrained problem: problem_w_asf = problem_w_asf.add_constraints( [ Constraint( name=f"_const_{i + 1}", symbol=f"_const_{i + 1}", func=f"{obj.symbol}_min - {previous_nav_point[obj.symbol] * (-1 if obj.maximize else 1)}", cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) for i, obj in enumerate(problem_w_asf.objectives) ] ) # solve the problem solver_instance = init_solver(problem_w_asf, _solver_options) return solver_instance.solve(target) ``` ### desdeo.mcdm.nautilus Functions related to the NAUTILUS 1/2 method are defined here. Reference of the method: TODO: update #### NAUTILUS_Response Bases: `BaseModel` The response of the NAUTILUS method. Source code in `desdeo/mcdm/nautilus.py` ``` class NAUTILUS_Response(BaseModel): # NOQA: N801 """The response of the NAUTILUS method.""" step_number: int = Field(description="The step number associted with this response.") distance_to_front: float = Field( description=( "The distance travelled to the Pareto front. " "The distance is a ratio of the distances between the nadir and navigation point, and " "the nadir and the reachable objective vector. The distance is given in percentage." ) ) preference: dict | None = Field( description="The preference used in the step. For now assumed that it is a reference point" ) # preference_method: dict | None = Field(description="The preference method used in the step.") # improvement_direction: dict | None = Field(description="The improvement direction.") navigation_point: dict = Field(description="The navigation point used in the step.") reachable_solution: dict | None = Field(description="The reachable solution found in the step.") reachable_bounds: dict = Field(description="The reachable bounds found in the step.") ``` #### NautilusError Bases: `Exception` Raised when an exception is encountered with procedures related to NAUTILUS. Source code in `desdeo/mcdm/nautilus.py` ``` class NautilusError(Exception): """Raised when an exception is encountered with procedures related to NAUTILUS.""" ``` #### \_\_nautilus_all_steps ``` __nautilus_all_steps( problem: Problem, steps_remaining: int, preference: dict, previous_responses: list[NAUTILUS_Response], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[NAUTILUS_Response] ``` Performs all steps of the NAUTILUS method. Warning Unused and broken; `steps_remaining > 1` raises TypeError. Commit e84cc462 (2024-04-08) removed `reachable_solution` from `nautilus_step` and left this caller behind, so the `else` branch below passes an argument that no longer exists -- and even if it did, `nautilus_step` now always recomputes the reachable solution, which is the opposite of what this function documents. `reachable_solution = dict` is also a typo for `{}`, and `preference` is only ever forwarded as `points`, never as `ranks`. Use `nautili_step` in `desdeo.mcdm.nautili` as the model if this is ever revived. NAUTILUS needs to be initialized before calling this function. Once initialized, this function performs all steps of the method. However, this method need not start from the beginning. The method conducts "steps_remaining" number of steps from the last navigation point. The last navigation point is taken from the last response in "previous_responses" list. The first step in this algorithm always involves recalculating the reachable solution. All subsequest steps are precalculated without recalculating the reachable solution, with the assumption that the reference point has not changed. It is up to the user to only show the steps that the DM thinks they have taken. Parameters: | Name | Type | Description | Default | | -------------------- | ------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | | `problem` | `Problem` | The problem to be solved. | *required* | | `steps_remaining` | `int` | The number of steps remaining. | *required* | | `preference` | `dict` | The points provided by the DM for defining preference. | *required* | | `previous_responses` | `list[NAUTILUS_Response]` | The previous responses of the method. | *required* | | `solver` | \`BaseSolver | None\` | The solver to use. Defaults to None, in which case the algorithm will guess the best solver for the problem. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Returns: | Type | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `list[NAUTILUS_Response]` | list\[NAUTILUS_Response\]: The new responses of the method after all steps. Note, as only new responses are returned, the length of the list is equal to "steps_remaining". The analyst should append these responses to the "previous_responses" list to keep track of the entire process. | Source code in `desdeo/mcdm/nautilus.py` ``` def __nautilus_all_steps( problem: Problem, steps_remaining: int, preference: dict, previous_responses: list[NAUTILUS_Response], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[NAUTILUS_Response]: """Performs all steps of the NAUTILUS method. Warning: Unused and broken; `steps_remaining > 1` raises TypeError. Commit e84cc462 (2024-04-08) removed `reachable_solution` from `nautilus_step` and left this caller behind, so the `else` branch below passes an argument that no longer exists -- and even if it did, `nautilus_step` now always recomputes the reachable solution, which is the opposite of what this function documents. `reachable_solution = dict` is also a typo for `{}`, and `preference` is only ever forwarded as `points`, never as `ranks`. Use `nautili_step` in `desdeo.mcdm.nautili` as the model if this is ever revived. NAUTILUS needs to be initialized before calling this function. Once initialized, this function performs all steps of the method. However, this method need not start from the beginning. The method conducts "steps_remaining" number of steps from the last navigation point. The last navigation point is taken from the last response in "previous_responses" list. The first step in this algorithm always involves recalculating the reachable solution. All subsequest steps are precalculated without recalculating the reachable solution, with the assumption that the reference point has not changed. It is up to the user to only show the steps that the DM thinks they have taken. Args: problem (Problem): The problem to be solved. steps_remaining (int): The number of steps remaining. preference (dict): The points provided by the DM for defining preference. previous_responses (list[NAUTILUS_Response]): The previous responses of the method. solver (BaseSolver | None, optional): The solver to use. Defaults to None, in which case the algorithm will guess the best solver for the problem. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Returns: list[NAUTILUS_Response]: The new responses of the method after all steps. Note, as only new responses are returned, the length of the list is equal to "steps_remaining". The analyst should append these responses to the "previous_responses" list to keep track of the entire process. """ responses: list[NAUTILUS_Response] = [] nav_point = previous_responses[-1].navigation_point step_number = previous_responses[-1].step_number + 1 first_iteration = True reachable_solution = dict while steps_remaining > 0: if first_iteration: response = nautilus_step( problem, steps_remaining=steps_remaining, step_number=step_number, nav_point=nav_point, points=preference, solver=solver, solver_options=solver_options, ) first_iteration = False else: # BROKEN: `nautilus_step` takes no `reachable_solution`. See the docstring. response = nautilus_step( problem, steps_remaining=steps_remaining, step_number=step_number, nav_point=nav_point, reachable_solution=reachable_solution, solver=solver, solver_options=solver_options, ) response.preference = preference responses.append(response) reachable_solution = response.reachable_solution nav_point = response.navigation_point steps_remaining -= 1 step_number += 1 return responses ``` #### calculate_preferential_factors ``` calculate_preferential_factors() ``` TODO: implement. Source code in `desdeo/mcdm/nautilus.py` ``` def calculate_preferential_factors(): """TODO: implement.""" ``` #### get_current_path ``` get_current_path( all_responses: list[NAUTILUS_Response], ) -> list[int] ``` Get the path of the current responses. All responses may contain steps that the DM has gone back on. This function returns the path of the current active path being followed by the DM. The path is a list of indices of the responses in the "all_responses" list. Note that the path includes all steps until reaching the Pareto front (or whatever the last response is). It is up to the analyst/GUI to only show the steps that the DM has taken. Parameters: | Name | Type | Description | Default | | --------------- | ------------------------- | ---------------------------------------------- | ---------- | | `all_responses` | `list[NAUTILUS_Response]` | All responses returned by the NAUTILUS method. | *required* | Returns: | Type | Description | | ----------- | ------------------------------------------------------ | | `list[int]` | list\[int\]: The path of the current active responses. | Source code in `desdeo/mcdm/nautilus.py` ``` def get_current_path(all_responses: list[NAUTILUS_Response]) -> list[int]: """Get the path of the current responses. All responses may contain steps that the DM has gone back on. This function returns the path of the current active path being followed by the DM. The path is a list of indices of the responses in the "all_responses" list. Note that the path includes all steps until reaching the Pareto front (or whatever the last response is). It is up to the analyst/GUI to only show the steps that the DM has taken. Args: all_responses (list[NAUTILUS_Response]): All responses returned by the NAUTILUS method. Returns: list[int]: The path of the current active responses. """ total_steps = all_responses[-1].step_number current_index = len(all_responses) - 1 path: list[int] = [current_index] total_steps -= 1 while total_steps >= 0: found_step = False while not found_step: current_index -= 1 if all_responses[current_index].step_number == total_steps: path.append(current_index) found_step = True total_steps -= 1 return list(reversed(path)) ``` #### nautilus_init ``` nautilus_init( problem: Problem, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> NAUTILUS_Response ``` Initializes the NAUTILUS method. Creates the initial response of the method, which sets the navigation point to the nadir point and the reachable bounds to the ideal and nadir points. Parameters: | Name | Type | Description | Default | | ---------------- | --------------- | ------------------------- | ----------------------------------------------------------------------------------- | | `problem` | `Problem` | The problem to be solved. | *required* | | `solver` | \`BaseSolver | None\` | The solver to use. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Returns: | Name | Type | Description | | ------------------- | ------------------- | ----------------------------------- | | `NAUTILUS_Response` | `NAUTILUS_Response` | The initial response of the method. | Source code in `desdeo/mcdm/nautilus.py` ``` def nautilus_init( problem: Problem, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None ) -> NAUTILUS_Response: """Initializes the NAUTILUS method. Creates the initial response of the method, which sets the navigation point to the nadir point and the reachable bounds to the ideal and nadir points. Args: problem (Problem): The problem to be solved. solver (BaseSolver | None, optional): The solver to use. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Returns: NAUTILUS_Response: The initial response of the method. """ nav_point = get_nadir_dict(problem) lower_bounds, upper_bounds = solve_reachable_bounds( problem, nav_point, solver=solver, solver_options=solver_options ) return NAUTILUS_Response( distance_to_front=0, navigation_point=nav_point, reachable_bounds={"lower_bounds": lower_bounds, "upper_bounds": upper_bounds}, reachable_solution=None, preference=None, step_number=0, ) ``` #### nautilus_step ``` nautilus_step( problem: Problem, steps_remaining: int, step_number: int, nav_point: dict, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, points: dict[str, float] | None = None, ranks: dict[str, int] | None = None, ) -> NAUTILUS_Response ``` Performs a step of the NAUTILUS method. Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ---------------------------------------------------- | ----------------------------------------------------------------------------------- | | `problem` | `Problem` | The problem to be solved. | *required* | | `steps_remaining` | `int` | The number of steps remaining. | *required* | | `step_number` | `int` | The current step number. Just used for the response. | *required* | | `nav_point` | `dict` | The current navigation point. | *required* | | `solver` | \`BaseSolver | None\` | The solver to use. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | | `points` | \`dict[str, float] | None\` | The points of the objectives. Defaults to None. | | `ranks` | \`dict[str, int] | None\` | The ranks of the objectives. Defaults to None. | Raises: | Type | Description | | --------------- | --------------------------------------------------------- | | `NautilusError` | If neither preference nor reachable_solution is provided. | | `NautilusError` | If both preference and reachable_solution are provided. | Returns: | Name | Type | Description | | ------------------- | ------------------- | ------------------------------------------ | | `NAUTILUS_Response` | `NAUTILUS_Response` | The response of the method after the step. | Source code in `desdeo/mcdm/nautilus.py` ``` def nautilus_step( problem: Problem, steps_remaining: int, step_number: int, nav_point: dict, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, points: dict[str, float] | None = None, ranks: dict[str, int] | None = None, ) -> NAUTILUS_Response: """Performs a step of the NAUTILUS method. Args: problem (Problem): The problem to be solved. steps_remaining (int): The number of steps remaining. step_number (int): The current step number. Just used for the response. nav_point (dict): The current navigation point. solver (BaseSolver | None, optional): The solver to use. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. points (dict[str, float] | None, optional): The points of the objectives. Defaults to None. ranks (dict[str, int] | None, optional): The ranks of the objectives. Defaults to None. Raises: NautilusError: If neither preference nor reachable_solution is provided. NautilusError: If both preference and reachable_solution are provided. Returns: NAUTILUS_Response: The response of the method after the step. """ if points is None and ranks is None: raise NautilusError("Either points or ranks must be provided.") if points is not None and ranks is not None: raise NautilusError("Both points and ranks cannot be provided.") # get weights if points is not None: # noqa: SIM108 weights = points_to_weights(points, problem) else: weights = ranks_to_weights(ranks, problem) # calculate reachable solution (direction). # This is inefficient as it is recalculated even if preferences do not change. opt_result = solve_reachable_solution(problem, weights, nav_point, solver, solver_options=solver_options) if not opt_result.success: warn(message="The solver did not converge.", stacklevel=2) reachable_point = opt_result.optimal_objectives # update nav point new_nav_point = calculate_navigation_point(problem, nav_point, reachable_point, steps_remaining) # update_bounds lower_bounds, upper_bounds = solve_reachable_bounds( problem, new_nav_point, solver, solver_options=solver_options ) distance = calculate_distance_to_front(problem, new_nav_point, reachable_point) return NAUTILUS_Response( step_number=step_number, distance_to_front=distance, navigation_point=new_nav_point, reachable_solution=reachable_point, preference=ranks if ranks is not None else points, reachable_bounds={"lower_bounds": lower_bounds, "upper_bounds": upper_bounds}, ) ``` #### points_to_weights ``` points_to_weights( points: dict[str, float], problem: Problem ) -> dict[str, float] ``` Convert points to weights. The points are converted to weights using the following formula: weight = point * (nadir - utopian). Parameters: | Name | Type | Description | Default | | --------- | ------------------ | ----------------------------- | ---------- | | `points` | `dict[str, float]` | The points of the objectives. | *required* | | `problem` | `Problem` | The problem being solved. | *required* | Returns: | Type | Description | | ------------------ | ----------------------------------------------------------- | | `dict[str, float]` | dict\[str, float\]: The weights calculated from the points. | Source code in `desdeo/mcdm/nautilus.py` ``` def points_to_weights(points: dict[str, float], problem: Problem) -> dict[str, float]: """Convert points to weights. The points are converted to weights using the following formula: weight = point * (nadir - utopian). Args: points (dict[str, float]): The points of the objectives. problem (Problem): The problem being solved. Returns: dict[str, float]: The weights calculated from the points. """ nadir = get_nadir_dict(problem) ideal = get_ideal_dict(problem) tol = 1e-6 weights = {} check_sum = 0 for key, point in points.items(): max_mult = next(obj.maximize for obj in problem.objectives if obj.symbol == key) max_mult = -1 if max_mult else 1 weights[key] = point / 100 * (nadir[key] * max_mult - ideal[key] * max_mult + tol) check_sum += point if check_sum != 100: # noqa: PLR2004 raise ValueError(f"The sum of the points must be 100. The sum is {check_sum}.") return weights ``` #### ranks_to_weights ``` ranks_to_weights( ranks: dict[str, int], problem: Problem ) -> dict[str, float] ``` Convert ranks to weights. The ranks are converted to weights using the following formula: weight = rank * (nadir - utopian). Note that this means that a lower rank is worse. Parameters: | Name | Type | Description | Default | | --------- | ---------------- | ---------------------------- | ---------- | | `ranks` | `dict[str, int]` | The ranks of the objectives. | *required* | | `problem` | `Problem` | The problem being solved. | *required* | Returns: | Type | Description | | ------------------ | ---------------------------------------------------------- | | `dict[str, float]` | dict\[str, float\]: The weights calculated from the ranks. | Source code in `desdeo/mcdm/nautilus.py` ``` def ranks_to_weights(ranks: dict[str, int], problem: Problem) -> dict[str, float]: """Convert ranks to weights. The ranks are converted to weights using the following formula: weight = rank * (nadir - utopian). Note that this means that a lower rank is worse. Args: ranks (dict[str, int]): The ranks of the objectives. problem (Problem): The problem being solved. Returns: dict[str, float]: The weights calculated from the ranks. """ nadir = get_nadir_dict(problem) ideal = get_ideal_dict(problem) tol = 1e-10 weights = {} for key, rank in ranks.items(): max_mult = next(obj.maximize for obj in problem.objectives if obj.symbol == key) max_mult = -1 if max_mult else 1 weights[key] = rank * (nadir[key] * max_mult - ideal[key] * max_mult + tol) return weights ``` #### solve_reachable_solution ``` solve_reachable_solution( problem: Problem, weights: dict[str, float], previous_nav_point: dict[str, float], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> SolverResults ``` Calculates the reachable solution on the Pareto optimal front. For the calculation to make sense in the context of NAUTILUS, the reference point should be bounded by the reachable bounds present at the navigation step the reference point has been given. In practice, the reachable solution is calculated by solving an achievement scalarizing function. Parameters: | Name | Type | Description | Default | | -------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `weights` | `dict[str, float]` | the weights defining the direction of improvement. Must be calculated from the preference provided by the DM (weights, ranks, or reference point). | *required* | | `previous_nav_point` | `dict[str, float]` | the previous navigation point. The reachable solution found is always better than the previous navigation point. | *required* | | `solver` | \`BaseSolver | None\` | solver to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Returns: | Name | Type | Description | | --------------- | --------------- | ------------------------------ | | `SolverResults` | `SolverResults` | the results of the projection. | Source code in `desdeo/mcdm/nautilus.py` ``` def solve_reachable_solution( problem: Problem, weights: dict[str, float], # improvement_direction: dict[str, float], previous_nav_point: dict[str, float], solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> SolverResults: """Calculates the reachable solution on the Pareto optimal front. For the calculation to make sense in the context of NAUTILUS, the reference point should be bounded by the reachable bounds present at the navigation step the reference point has been given. In practice, the reachable solution is calculated by solving an achievement scalarizing function. Args: problem (Problem): the problem being solved. weights (dict[str, float]): the weights defining the direction of improvement. Must be calculated from the preference provided by the DM (weights, ranks, or reference point). previous_nav_point (dict[str, float]): the previous navigation point. The reachable solution found is always better than the previous navigation point. solver (BaseSolver | None, optional): solver to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Returns: SolverResults: the results of the projection. """ # check solver init_solver = guess_best_solver(problem) if solver is None else solver _solver_options = None if solver_options is None or solver is None else solver_options # need to convert the preferences to preferential factors? # create and add scalarization function if problem.is_twice_differentiable: # differentiable problem problem_w_asf, target = add_asf_generic_diff( problem, symbol="asf", reference_point=previous_nav_point, weights=weights, reference_point_aug=previous_nav_point, ) else: # non-differentiable problem problem_w_asf, target = add_asf_generic_nondiff( problem, symbol="asf", reference_point=previous_nav_point, weights=weights, reference_point_aug=previous_nav_point, ) # Note: We do not solve the global problem. Instead, we solve this constrained problem: problem_w_asf = problem_w_asf.add_constraints( [ Constraint( name=f"_const_{i + 1}", symbol=f"_const_{i + 1}", func=f"{obj.symbol}_min - {previous_nav_point[obj.symbol] * (-1 if obj.maximize else 1)}", cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) for i, obj in enumerate(problem_w_asf.objectives) ] ) # solve the problem solver_instance = init_solver(problem_w_asf, _solver_options) return solver_instance.solve(target) ``` #### step_back_index ``` step_back_index( responses: list[NAUTILUS_Response], step_number: int ) -> int ``` Find the index of the response with the given step number. Note, multiple responses can have the same step number. This may happen if the DM takes a step back. In this case, the latest response with the given step number is returned. Note, as we precalculate all the responses, it is up to the analyst to show the steps that the DM thinks they have taken. Without this, the DM may be confused. In the worst case, the DM may take a step "back to the future". Parameters: | Name | Type | Description | Default | | ------------- | ------------------------- | ------------------------------------------ | ---------- | | `responses` | `list[NAUTILUS_Response]` | Responses returned by the NAUTILUS method. | *required* | | `step_number` | `int` | The step number to go back to. | *required* | Returns: | Name | Type | Description | | ----- | ----- | ----------------------------------------------------- | | `int` | `int` | The index of the response with the given step number. | Source code in `desdeo/mcdm/nautilus.py` ``` def step_back_index(responses: list[NAUTILUS_Response], step_number: int) -> int: """Find the index of the response with the given step number. Note, multiple responses can have the same step number. This may happen if the DM takes a step back. In this case, the latest response with the given step number is returned. Note, as we precalculate all the responses, it is up to the analyst to show the steps that the DM thinks they have taken. Without this, the DM may be confused. In the worst case, the DM may take a step "back to the future". Args: responses (list[NAUTILUS_Response]): Responses returned by the NAUTILUS method. step_number (int): The step number to go back to. Returns: int : The index of the response with the given step number. """ relevant_indices = [i for i, response in enumerate(responses) if response.step_number == step_number] # Choose latest index return relevant_indices[-1] ``` ### desdeo.mcdm.nautilus_navigator Functions related to the NAUTILUS Navigator method are defined here. Reference of the method: Ruiz, Ana B., et al. "NAUTILUS Navigator: free search interactive multiobjective optimization without trading-off." Journal of Global Optimization 74.2 (2019): 213-231. #### NAUTILUS_Response Bases: `BaseModel` The response of the NAUTILUS Navigator method. Source code in `desdeo/mcdm/nautilus_navigator.py` ``` class NAUTILUS_Response(BaseModel): # NOQA: N801 """The response of the NAUTILUS Navigator method.""" step_number: int = Field(description="The step number associted with this response.") distance_to_front: float = Field( description=( "The distance travelled to the Pareto front. " "The distance is a ratio of the distances between the nadir and navigation point, and " "the nadir and the reachable objective vector. The distance is given in percentage." ) ) reference_point: dict | None = Field(description="The reference point used in the step.") bounds: dict | None = Field(description="The user provided bounds.") navigation_point: dict = Field(description="The navigation point used in the step.") reachable_solution: dict | None = Field(description="The reachable solution found in the step.") reachable_bounds: dict = Field(description="The reachable bounds found in the step.") ``` #### NautilusNavigatorError Bases: `Exception` Raised when an exception is encountered with procedures related to NAUTILUS Navigator. Source code in `desdeo/mcdm/nautilus_navigator.py` ``` class NautilusNavigatorError(Exception): """Raised when an exception is encountered with procedures related to NAUTILUS Navigator.""" ``` #### calculate_distance_to_front ``` calculate_distance_to_front( problem: Problem, navigation_point: dict[str, float], reachable_objective_vector: dict[str, float], ) -> float ``` Calculates the distance to the Pareto optimal front from a navigation point. It is assumed that a nadir point is defined for the problem. Parameters: | Name | Type | Description | Default | | ---------------------------- | ------------------ | ----------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem being solved. | *required* | | `navigation_point` | `dict[str, float]` | the current navigation point. | *required* | | `reachable_objective_vector` | `dict[str, float]` | the current reachable objective vector from the navigation point. | *required* | Raises: | Type | Description | | ------------------------ | --------------------------------------------------------------------------- | | `NautilusNavigatorError` | all or some of the components of the problem's nadir point are not defined. | Returns: | Name | Type | Description | | ------- | ------- | -------------------------- | | `float` | `float` | the distance to the front. | Source code in `desdeo/mcdm/nautilus_navigator.py` ``` def calculate_distance_to_front( problem: Problem, navigation_point: dict[str, float], reachable_objective_vector: dict[str, float] ) -> float: """Calculates the distance to the Pareto optimal front from a navigation point. It is assumed that a nadir point is defined for the problem. Args: problem (Problem): the problem being solved. navigation_point (dict[str, float]): the current navigation point. reachable_objective_vector (dict[str, float]): the current reachable objective vector from the navigation point. Raises: NautilusNavigatorError: all or some of the components of the problem's nadir point are not defined. Returns: float: the distance to the front. """ nadir_point = objective_dict_to_numpy_array(problem, get_nadir_dict(problem)) if None in nadir_point: msg = ( f"Some or all the nadir values for the given problem are 'None': {nadir_point}. " "The nadir point must be fully defined." ) raise NautilusNavigatorError(msg) z_nav = objective_dict_to_numpy_array(problem, navigation_point) f = objective_dict_to_numpy_array(problem, reachable_objective_vector) return (np.linalg.norm(z_nav - nadir_point) / np.linalg.norm(f - nadir_point)) * 100 ``` #### calculate_navigation_point ``` calculate_navigation_point( problem: Problem, previous_navigation_point: dict[str, float], reachable_objective_vector: dict[str, float], number_of_steps_remaining: int, ) -> dict[str, float] ``` Calculates the navigation point. The navigation point based on the previous navigation point, number of navigation steps remaining, and the reachable objective vector from the new navigation point. Parameters: | Name | Type | Description | Default | | ---------------------------- | ------------------ | ------------------------------------------------------------------------ | ---------- | | `problem` | `Problem` | the problem being solved. | *required* | | `previous_navigation_point` | `dict[str, float]` | the previous navigation point. | *required* | | `reachable_objective_vector` | `dict[str, float]` | the current reachable objective vector from the navigation point. | *required* | | `number_of_steps_remaining` | `int` | the number of steps remaining in the navigation. Must be greater than 0. | *required* | Raises: | Type | Description | | ------------------------ | -------------------------------------------------------- | | `NautilusNavigatorError` | when the given number of steps remaining is less than 0. | Returns: | Type | Description | | ------------------ | ------------------------------------ | | `dict[str, float]` | list\[float\]: the navigation point. | Source code in `desdeo/mcdm/nautilus_navigator.py` ``` def calculate_navigation_point( problem: Problem, previous_navigation_point: dict[str, float], reachable_objective_vector: dict[str, float], number_of_steps_remaining: int, ) -> dict[str, float]: """Calculates the navigation point. The navigation point based on the previous navigation point, number of navigation steps remaining, and the reachable objective vector from the new navigation point. Args: problem (Problem): the problem being solved. previous_navigation_point (dict[str, float]): the previous navigation point. reachable_objective_vector (dict[str, float]): the current reachable objective vector from the navigation point. number_of_steps_remaining (int): the number of steps remaining in the navigation. Must be greater than 0. Raises: NautilusNavigatorError: when the given number of steps remaining is less than 0. Returns: list[float]: the navigation point. """ if number_of_steps_remaining <= 0: msg = f"The given number of steps remaining ({number_of_steps_remaining=}) must be greater than 0." raise NautilusNavigatorError(msg) z_prev = objective_dict_to_numpy_array(problem, previous_navigation_point) f = objective_dict_to_numpy_array(problem, reachable_objective_vector).T rs = number_of_steps_remaining # return the new navigation point z = ((rs - 1) / (rs)) * z_prev + f / rs return numpy_array_to_objective_dict(problem, z) ``` #### get_current_path ``` get_current_path( all_responses: list[NAUTILUS_Response], ) -> list[int] ``` Get the path of the current responses. All responses may contain steps that the DM has gone back on. This function returns the path of the current active path being followed by the DM. The path is a list of indices of the responses in the "all_responses" list. Note that the path includes all steps until reaching the Pareto front (or whatever the last response is). It is up to the analyst/GUI to only show the steps that the DM has taken. Parameters: | Name | Type | Description | Default | | --------------- | ------------------------- | ---------------------------------------------- | ---------- | | `all_responses` | `list[NAUTILUS_Response]` | All responses returned by the NAUTILUS method. | *required* | Returns: | Type | Description | | ----------- | ------------------------------------------------------ | | `list[int]` | list\[int\]: The path of the current active responses. | Source code in `desdeo/mcdm/nautilus_navigator.py` ``` def get_current_path(all_responses: list[NAUTILUS_Response]) -> list[int]: """Get the path of the current responses. All responses may contain steps that the DM has gone back on. This function returns the path of the current active path being followed by the DM. The path is a list of indices of the responses in the "all_responses" list. Note that the path includes all steps until reaching the Pareto front (or whatever the last response is). It is up to the analyst/GUI to only show the steps that the DM has taken. Args: all_responses (list[NAUTILUS_Response]): All responses returned by the NAUTILUS method. Returns: list[int]: The path of the current active responses. """ total_steps = all_responses[-1].step_number current_index = len(all_responses) - 1 path: list[int] = [current_index] total_steps -= 1 while total_steps >= 0: found_step = False while not found_step: current_index -= 1 if all_responses[current_index].step_number == total_steps: path.append(current_index) found_step = True total_steps -= 1 return list(reversed(path)) ``` #### navigator_all_steps ``` navigator_all_steps( problem: Problem, steps_remaining: int, reference_point: dict, previous_responses: list[NAUTILUS_Response], bounds: dict | None = None, solver: BaseSolver | None = None, ) -> list[NAUTILUS_Response] ``` Performs all steps of the NAUTILUS method. NAUTILUS needs to be initialized before calling this function. Once initialized, this function performs all steps of the method. However, this method need not start from the beginning. The method conducts "steps_remaining" number of steps from the last navigation point. The last navigation point is taken from the last response in "previous_responses" list. The first step in this algorithm always involves recalculating the reachable solution. All subsequest steps are precalculated without recalculating the reachable solution, with the assumption that the reference point has not changed. It is up to the user to only show the steps that the DM thinks they have taken. Parameters: | Name | Type | Description | Default | | -------------------- | ------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `problem` | `Problem` | The problem to be solved. | *required* | | `steps_remaining` | `int` | The number of steps remaining. | *required* | | `reference_point` | `dict` | The reference point provided by the DM. | *required* | | `bounds` | `dict` | The bounds of the problem provided by the DM. | `None` | | `previous_responses` | `list[NAUTILUS_Response]` | The previous responses of the method. | *required* | | `solver` | \`BaseSolver | None\` | The solver to use. Defaults to None, in which case the algorithm will guess the best solver for the problem. | Returns: | Type | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `list[NAUTILUS_Response]` | list\[NAUTILUS_Response\]: The new responses of the method after all steps. Note, as only new responses are returned, the length of the list is equal to "steps_remaining". The analyst should append these responses to the "previous_responses" list to keep track of the entire process. | Source code in `desdeo/mcdm/nautilus_navigator.py` ``` def navigator_all_steps( problem: Problem, steps_remaining: int, reference_point: dict, previous_responses: list[NAUTILUS_Response], bounds: dict | None = None, solver: BaseSolver | None = None, ) -> list[NAUTILUS_Response]: """Performs all steps of the NAUTILUS method. NAUTILUS needs to be initialized before calling this function. Once initialized, this function performs all steps of the method. However, this method need not start from the beginning. The method conducts "steps_remaining" number of steps from the last navigation point. The last navigation point is taken from the last response in "previous_responses" list. The first step in this algorithm always involves recalculating the reachable solution. All subsequest steps are precalculated without recalculating the reachable solution, with the assumption that the reference point has not changed. It is up to the user to only show the steps that the DM thinks they have taken. Args: problem (Problem): The problem to be solved. steps_remaining (int): The number of steps remaining. reference_point (dict): The reference point provided by the DM. bounds (dict): The bounds of the problem provided by the DM. previous_responses (list[NAUTILUS_Response]): The previous responses of the method. solver (BaseSolver | None, optional): The solver to use. Defaults to None, in which case the algorithm will guess the best solver for the problem. Returns: list[NAUTILUS_Response]: The new responses of the method after all steps. Note, as only new responses are returned, the length of the list is equal to "steps_remaining". The analyst should append these responses to the "previous_responses" list to keep track of the entire process. """ responses: list[NAUTILUS_Response] = [] nav_point = previous_responses[-1].navigation_point step_number = previous_responses[-1].step_number + 1 first_iteration = True reachable_solution = dict while steps_remaining > 0: if first_iteration: response = navigator_step( problem, steps_remaining=steps_remaining, step_number=step_number, nav_point=nav_point, reference_point=reference_point, bounds=bounds, solver=solver, ) first_iteration = False else: response = navigator_step( problem, steps_remaining=steps_remaining, step_number=step_number, nav_point=nav_point, reachable_solution=reachable_solution, bounds=bounds, solver=solver, ) response.reference_point = reference_point responses.append(response) reachable_solution = response.reachable_solution nav_point = response.navigation_point steps_remaining -= 1 step_number += 1 return responses ``` #### navigator_init ``` navigator_init( problem: Problem, solver: BaseSolver | None = None ) -> NAUTILUS_Response ``` Initializes the NAUTILUS method. Creates the initial response of the method, which sets the navigation point to the nadir point and the reachable bounds to the ideal and nadir points. Parameters: | Name | Type | Description | Default | | --------- | ------------ | ------------------------- | ------------------------------------ | | `problem` | `Problem` | The problem to be solved. | *required* | | `solver` | \`BaseSolver | None\` | The solver to use. Defaults to None. | Returns: | Name | Type | Description | | ------------------- | ------------------- | ----------------------------------- | | `NAUTILUS_Response` | `NAUTILUS_Response` | The initial response of the method. | Source code in `desdeo/mcdm/nautilus_navigator.py` ``` def navigator_init(problem: Problem, solver: BaseSolver | None = None) -> NAUTILUS_Response: """Initializes the NAUTILUS method. Creates the initial response of the method, which sets the navigation point to the nadir point and the reachable bounds to the ideal and nadir points. Args: problem (Problem): The problem to be solved. solver (BaseSolver | None, optional): The solver to use. Defaults to None. Returns: NAUTILUS_Response: The initial response of the method. """ nav_point = get_nadir_dict(problem) lower_bounds, upper_bounds = solve_reachable_bounds(problem, nav_point, solver=solver) return NAUTILUS_Response( distance_to_front=0, navigation_point=nav_point, reachable_bounds={"lower_bounds": lower_bounds, "upper_bounds": upper_bounds}, reachable_solution=None, reference_point=None, bounds=None, step_number=0, ) ``` #### navigator_step ``` navigator_step( problem: Problem, steps_remaining: int, step_number: int, nav_point: dict, bounds: dict | None = None, solver: BaseSolver | None = None, reference_point: dict | None = None, reachable_solution: dict[str, float] | None = None, ) -> NAUTILUS_Response ``` Performs a step of the NAUTILUS method. Parameters: | Name | Type | Description | Default | | -------------------- | ------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `problem` | `Problem` | The problem to be solved. | *required* | | `steps_remaining` | `int` | The number of steps remaining. | *required* | | `step_number` | `int` | The current step number. Just used for the response. | *required* | | `nav_point` | `dict` | The current navigation point. | *required* | | `solver` | \`BaseSolver | None\` | The solver to use. Defaults to None. | | `reference_point` | \`dict | None\` | The reference point provided by the DM. Defaults to None, in which case it is assumed that the DM has not changed their preference. The algorithm uses the last reachable solution, which must be provided in this case. | | `bounds` | \`dict | None\` | The bounds of the problem provided by the DM. Defaults to None. | | `reachable_solution` | \`dict | None\` | The previous reachable solution. Must only be provided if the DM has not changed their preference. Defaults to None. | Raises: | Type | Description | | ------------------------ | -------------------------------------------------------------- | | `NautilusNavigatorError` | If neither reference_point nor reachable_solution is provided. | | `NautilusNavigatorError` | If both reference_point and reachable_solution are provided. | Returns: | Name | Type | Description | | ------------------- | ------------------- | ------------------------------------------ | | `NAUTILUS_Response` | `NAUTILUS_Response` | The response of the method after the step. | Source code in `desdeo/mcdm/nautilus_navigator.py` ``` def navigator_step( problem: Problem, steps_remaining: int, step_number: int, nav_point: dict, bounds: dict | None = None, solver: BaseSolver | None = None, reference_point: dict | None = None, reachable_solution: dict[str, float] | None = None, ) -> NAUTILUS_Response: """Performs a step of the NAUTILUS method. Args: problem (Problem): The problem to be solved. steps_remaining (int): The number of steps remaining. step_number (int): The current step number. Just used for the response. nav_point (dict): The current navigation point. solver (BaseSolver | None, optional): The solver to use. Defaults to None. reference_point (dict | None, optional): The reference point provided by the DM. Defaults to None, in which case it is assumed that the DM has not changed their preference. The algorithm uses the last reachable solution, which must be provided in this case. bounds (dict | None, optional): The bounds of the problem provided by the DM. Defaults to None. reachable_solution (dict | None, optional): The previous reachable solution. Must only be provided if the DM has not changed their preference. Defaults to None. Raises: NautilusNavigatorError: If neither reference_point nor reachable_solution is provided. NautilusNavigatorError: If both reference_point and reachable_solution are provided. Returns: NAUTILUS_Response: The response of the method after the step. """ if reference_point is None and reachable_solution is None: raise NautilusNavigatorError("Either reference_point or reachable_solution must be provided.") if reference_point is not None and reachable_solution is not None: raise NautilusNavigatorError("Only one of reference_point or reachable_solution should be provided.") if reference_point is not None: opt_result = solve_reachable_solution(problem, reference_point, nav_point, solver, bounds=bounds) reachable_point = opt_result.optimal_objectives elif reachable_solution is not None: reachable_point = reachable_solution # update nav point new_nav_point = calculate_navigation_point(problem, nav_point, reachable_point, steps_remaining) # update_bounds lower_bounds, upper_bounds = solve_reachable_bounds(problem, new_nav_point, solver=solver, bounds=bounds) distance = calculate_distance_to_front(problem, new_nav_point, reachable_point) if bounds is None: bounds = {obj.symbol: obj.nadir for obj in problem.objectives} return NAUTILUS_Response( step_number=step_number, distance_to_front=distance, navigation_point=new_nav_point, reachable_solution=reachable_point, reference_point=reference_point, reachable_bounds={"lower_bounds": lower_bounds, "upper_bounds": upper_bounds}, bounds=bounds, ) ``` #### solve_reachable_bounds ``` solve_reachable_bounds( problem: Problem, navigation_point: dict[str, float], bounds: dict[str, float] | None = None, solver: BaseSolver | None = None, bound_th: float = 0.001, ) -> tuple[dict[str, float], dict[str, float]] ``` Computes the current reachable (upper and lower) bounds of the solutions in the objective space. The reachable bound are computed based on the current navigation point. The bounds are computed by solving an epsilon constraint problem. Parameters: | Name | Type | Description | Default | | ------------------ | ------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `navigation_point` | `dict[str, float]` | the navigation point limiting the reachable area. The key is the objective function's symbol and the value the navigation point. | *required* | | `bounds` | `dict[str, float]` | the user provided bounds preference. | `None` | | `solver` | \`BaseSolver | None\` | solver used to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. | | `bound_th` | `float` | a threshold for comparing the bounds to the set epsilon constraints. | `0.001` | Raises: | Type | Description | | ------------------------- | --------------------------------------------------------------------- | | `NautilusNavigationError` | when optimization of an epsilon constraint problem is not successful. | Returns: | Type | Description | | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `tuple[dict[str, float], dict[str, float]]` | tuple\[dict[str, float], dict[str, float]\]: a tuple of dicts, where the first dict are the lower bounds and the second element the upper bounds, the key is the symbol of each objective. | Source code in `desdeo/mcdm/nautilus_navigator.py` ``` def solve_reachable_bounds( problem: Problem, navigation_point: dict[str, float], bounds: dict[str, float] | None = None, solver: BaseSolver | None = None, bound_th: float = 1e-3, ) -> tuple[dict[str, float], dict[str, float]]: """Computes the current reachable (upper and lower) bounds of the solutions in the objective space. The reachable bound are computed based on the current navigation point. The bounds are computed by solving an epsilon constraint problem. Args: problem (Problem): the problem being solved. navigation_point (dict[str, float]): the navigation point limiting the reachable area. The key is the objective function's symbol and the value the navigation point. bounds (dict[str, float]): the user provided bounds preference. solver (BaseSolver | None, optional): solver used to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. bound_th (float, optional): a threshold for comparing the bounds to the set epsilon constraints. Raises: NautilusNavigationError: when optimization of an epsilon constraint problem is not successful. Returns: tuple[dict[str, float], dict[str, float]]: a tuple of dicts, where the first dict are the lower bounds and the second element the upper bounds, the key is the symbol of each objective. """ # If an objective is to be maximized, then the navigation point component of that objective should be # multiplied by -1. const_bounds = { objective.symbol: -1 * navigation_point[objective.symbol] if objective.maximize else navigation_point[objective.symbol] for objective in problem.objectives } # if a solver creator was provided, use that, else, guess the best one solver_init = guess_best_solver(problem) if solver is None else solver lower_bounds = {} upper_bounds = {} for objective in problem.objectives: # Lower bounds eps_problem, target, _ = add_epsilon_constraints( problem, "target", {f"{obj.symbol}": f"{obj.symbol}_eps" for obj in problem.objectives}, objective.symbol, const_bounds, ) # User bounds if bounds is not None: bound_constraints = [ Constraint( name=f"User bound for {obj.symbol}", symbol=f"{obj.symbol}_user", func=f"{obj.symbol}_min - {bounds[obj.symbol] * (-1 if obj.maximize else 1)}", cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) for obj in problem.objectives ] eps_problem = eps_problem.add_constraints(bound_constraints) # solve solver_instance = solver_init(eps_problem) res = solver_instance.solve(target) if not res.success: # could not optimize eps problem msg = ( f"Optimizing the epsilon constrait problem for the objective " f"{objective.symbol} was not successful. Reason: {res.message}" ) raise NautilusNavigatorError(msg) lower_bound = res.optimal_objectives[objective.symbol] if isinstance(lower_bound, list): lower_bound = lower_bound[0] # solver upper bounds eps_problem, target, _ = add_epsilon_constraints( problem, "target", {f"{obj.symbol}": f"{obj.symbol}_eps" for obj in problem.objectives}, objective.symbol, const_bounds, ) # We need to add a constrant related to the target objective to bound it to the navigation point # Maybe there should be a replacement to "create_epsilon_constraints_json" that allows for this # for now, we will add the constraint manually # target_expr[1] = -1 # maximize the objective target = "target" max_objective_scal = ScalarizationFunction( symbol=target, name="Max objective", func=["Negate", f"{objective.symbol}_min"], is_linear=objective.is_linear, is_convex=objective.is_convex, is_twice_differentiable=objective.is_twice_differentiable, ) eps_problem = problem.add_scalarization(max_objective_scal) bound_to_nav_constraint = Constraint( symbol=f"{objective.symbol}_to_bound", name=f"To bound {objective.symbol} to user bounds", func=["Add", f"{objective.symbol}_min", ["Negate", const_bounds[objective.symbol]]], cons_type=ConstraintTypeEnum.LTE, is_linear=objective.is_linear, is_convex=objective.is_convex, is_twice_differentiable=objective.is_twice_differentiable, ) # User bounds, add constraints if bounds is not None: bound_constraints = [ Constraint( name=f"User bound for {obj.symbol}", symbol=f"{obj.symbol}_user", func=f"{obj.symbol}_min - {bounds[obj.symbol] * (-1 if obj.maximize else 1)}", cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) for obj in problem.objectives ] eps_problem = eps_problem.add_constraints([bound_to_nav_constraint, *bound_constraints]) else: eps_problem = eps_problem.add_constraints([bound_to_nav_constraint]) # solve solver_instance = solver_init(eps_problem) res = solver_instance.solve(target) if not res.success: # could not optimize eps problem msg = ( f"Optimizing the epsilon constrait problem for the objective " f"{objective.symbol} was not successful. Reason: {res.message}" ) raise NautilusNavigatorError(msg) upper_bound = res.optimal_objectives[objective.symbol] if isinstance(upper_bound, list): upper_bound = upper_bound[0] if not (abs(upper_bound * (-1 if objective.maximize else 1) - const_bounds[objective.symbol]) < bound_th) and ( upper_bound * (-1 if objective.maximize else 1) > const_bounds[objective.symbol] ): msg = "The upper bound is worse than the navigation point. This should not happen." raise NautilusNavigatorError(msg) # add the lower and upper bounds logically depending whether an objective is to be maximized or minimized lower_bounds[objective.symbol] = lower_bound if not objective.maximize else upper_bound upper_bounds[objective.symbol] = upper_bound if not objective.maximize else lower_bound return lower_bounds, upper_bounds ``` #### solve_reachable_solution ``` solve_reachable_solution( problem: Problem, reference_point: dict[str, float], previous_nav_point: dict[str, float], solver: BaseSolver | None = None, bounds: dict[str, float] | None = None, ) -> SolverResults ``` Calculates the reachable solution on the Pareto optimal front. For the calculation to make sense in the context of NAUTILUS Navigator, the reference point should be bounded by the reachable bounds present at the navigation step the reference point has been given. In practice, the reachable solution is calculated by solving an achievement scalarizing function. Parameters: | Name | Type | Description | Default | | -------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `reference_point` | `dict[str, float]` | the reference point to project on the Pareto optimal front. | *required* | | `previous_nav_point` | `dict[str, float]` | the previous navigation point. The reachable solution found is always better than the previous navigation point. | *required* | | `solver` | \`BaseSolver | None\` | solver to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. | | `bounds` | \`dict[str, float] | None\` | the bounds of the problem. Defaults to None. | Returns: | Name | Type | Description | | --------------- | --------------- | ------------------------------ | | `SolverResults` | `SolverResults` | the results of the projection. | Source code in `desdeo/mcdm/nautilus_navigator.py` ``` def solve_reachable_solution( problem: Problem, reference_point: dict[str, float], previous_nav_point: dict[str, float], solver: BaseSolver | None = None, bounds: dict[str, float] | None = None, ) -> SolverResults: """Calculates the reachable solution on the Pareto optimal front. For the calculation to make sense in the context of NAUTILUS Navigator, the reference point should be bounded by the reachable bounds present at the navigation step the reference point has been given. In practice, the reachable solution is calculated by solving an achievement scalarizing function. Args: problem (Problem): the problem being solved. reference_point (dict[str, float]): the reference point to project on the Pareto optimal front. previous_nav_point (dict[str, float]): the previous navigation point. The reachable solution found is always better than the previous navigation point. solver (BaseSolver | None, optional): solver to solve the problem. If None, then a solver is utilized bases on the problem's properties. Defaults to None. bounds (dict[str, float] | None, optional): the bounds of the problem. Defaults to None. Returns: SolverResults: the results of the projection. """ # check solver init_solver = guess_best_solver(problem) if solver is None else solver # create and add scalarization function if problem.is_twice_differentiable: # differentiable problem problem_w_asf, target = add_asf_diff( problem, symbol="asf", reference_point=reference_point, # TODO: reference_in_aug=True ) else: # non-differentiable problem problem_w_asf, target = add_asf_nondiff( problem, symbol="asf", reference_point=reference_point, reference_in_aug=True ) # Note: We do not solve the global problem. Instead, we solve this constrained problem: constraints = [ Constraint( name=f"_const_{i + 1}", symbol=f"_const_{i + 1}", func=f"{obj.symbol}_min - {previous_nav_point[obj.symbol] * (-1 if obj.maximize else 1)}", cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) for i, obj in enumerate(problem.objectives) ] if bounds is not None: constraints += [ Constraint( name=f"_const_bound_{i + 1}", symbol=f"_const_bound_{i + 1}", cons_type=ConstraintTypeEnum.LTE, func=f"{obj.symbol}_min - {bounds[obj.symbol] * (-1 if obj.maximize else 1)}", is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) for i, obj in enumerate(problem.objectives) ] problem_w_asf = problem_w_asf.add_constraints(constraints) # solve the problem solver_instance = init_solver(problem_w_asf) return solver_instance.solve(target) ``` #### step_back_index ``` step_back_index( responses: list[NAUTILUS_Response], step_number: int ) -> int ``` Find the index of the response with the given step number. Note, multiple responses can have the same step number. This may happen if the DM takes a step back. In this case, the latest response with the given step number is returned. Note, as we precalculate all the responses, it is up to the analyst to show the steps that the DM thinks they have taken. Without this, the DM may be confused. In the worst case, the DM may take a step "back to the future". Parameters: | Name | Type | Description | Default | | ------------- | ------------------------- | ------------------------------------------ | ---------- | | `responses` | `list[NAUTILUS_Response]` | Responses returned by the NAUTILUS method. | *required* | | `step_number` | `int` | The step number to go back to. | *required* | Returns: | Name | Type | Description | | ----- | ----- | ----------------------------------------------------- | | `int` | `int` | The index of the response with the given step number. | Source code in `desdeo/mcdm/nautilus_navigator.py` ``` def step_back_index(responses: list[NAUTILUS_Response], step_number: int) -> int: """Find the index of the response with the given step number. Note, multiple responses can have the same step number. This may happen if the DM takes a step back. In this case, the latest response with the given step number is returned. Note, as we precalculate all the responses, it is up to the analyst to show the steps that the DM thinks they have taken. Without this, the DM may be confused. In the worst case, the DM may take a step "back to the future". Args: responses (list[NAUTILUS_Response]): Responses returned by the NAUTILUS method. step_number (int): The step number to go back to. Returns: int : The index of the response with the given step number. """ relevant_indices = [i for i, response in enumerate(responses) if response.step_number == step_number] # Choose latest index return relevant_indices[-1] ``` ### desdeo.mcdm.pareto_navigator Functions related to the Pareto Navigator method are defined here. Reference of the method: Eskelinen, Petri, et al. "Pareto navigator for interactive nonlinear multiobjective optimization." OR spectrum 32 (2010): 211-227. #### calculate_adjusted_speed ``` calculate_adjusted_speed( allowed_speeds: list[int], speed: float, scalar: float | None = 20, ) -> float ``` Calculate an adjusted speed from a given float. Note Adjusting the speed is not specified in the article but seems necessary. Parameters: | Name | Type | Description | Default | | ---------------- | --------- | --------------------------- | -------------------------------------------- | | `allowed_speeds` | `ndarray` | An array of allowed speeds. | *required* | | `speed` | `float` | A given speed value where. | *required* | | `scalar` | \`float | None(optional)\` | A scale to adjust the speed. Defaults to 20. | Returns: | Name | Type | Description | | ------- | ------- | ------------------------------------------------------------------------ | | `float` | `float` | An adjusted speed value calculated from given float. Is between 0 and 1. | Source code in `desdeo/mcdm/pareto_navigator.py` ``` def calculate_adjusted_speed(allowed_speeds: list[int], speed: float, scalar: float | None = 20) -> float: """Calculate an adjusted speed from a given float. Note: Adjusting the speed is not specified in the article but seems necessary. Args: allowed_speeds (np.ndarray): An array of allowed speeds. speed (float): A given speed value where. scalar (float | None (optional)): A scale to adjust the speed. Defaults to 20. Returns: float: An adjusted speed value calculated from given float. Is between 0 and 1. """ return (speed / np.max(allowed_speeds)) / scalar ``` #### calculate_all_solutions ``` calculate_all_solutions( problem: Problem, current_solution: dict[str, float], alpha: float, num_solutions: int, pref_info: dict, ) -> list[dict[str, float]] ``` Performs a set number of steps in the current direction. Parameters: | Name | Type | Description | Default | | ------------------ | ------------------ | --------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | | `current_solution` | `dict[str, float]` | The current solution. | *required* | | `alpha` | `float` | Step size. Between 0 and 1. | *required* | | `num_solutions` | `int` | Number of solutions calculated. | *required* | | `pref_info` | `dict` | Preference information. Either "reference_point" or "classification". | *required* | Returns: | Type | Description | | ------------------------ | ----------------------------------------------------------- | | `list[dict[str, float]]` | list\[dict[str, float]\]: A list of the computed solutions. | Source code in `desdeo/mcdm/pareto_navigator.py` ``` def calculate_all_solutions( problem: Problem, current_solution: dict[str, float], alpha: float, num_solutions: int, pref_info: dict ) -> list[dict[str, float]]: """Performs a set number of steps in the current direction. Args: problem (Problem): The problem being solved. current_solution (dict[str, float]): The current solution. alpha (float): Step size. Between 0 and 1. num_solutions (int): Number of solutions calculated. pref_info (dict): Preference information. Either "reference_point" or "classification". Returns: list[dict[str, float]]: A list of the computed solutions. """ solution = current_solution # check if the preference information is given as a reference point or as classification # and calculate the search direction based on the preference information if "reference_point" in pref_info: reference_point = pref_info["reference_point"] d = calculate_search_direction(problem, reference_point, current_solution) elif "classification" in pref_info: reference_point = classification_to_reference_point(problem, pref_info["classification"], solution) d = calculate_search_direction(problem, reference_point, solution) # the A matrix and b vector from the polyhedral set equation matrix_a, b = get_polyhedral_set(problem) # the A' matrix from the linear parametric programming problem matrix_a_new = construct_matrix_a(problem, matrix_a) solutions: list[dict[str, float]] = [] while len(solutions) < num_solutions: solution = calculate_next_solution(problem, d, solution, alpha, matrix_a_new, b) solutions.append(solution) return solutions ``` #### calculate_next_solution ``` calculate_next_solution( problem: Problem, search_direction: dict[str, float], current_solution: dict[str, float], alpha: float, matrix_a: ndarray, b: ndarray, ) -> dict[str, float] ``` Calculate the next solution. Parameters: | Name | Type | Description | Default | | ------------------ | ------------------ | ------------------------------ | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | | `search_direction` | `dict[str, float]` | The search direction. | *required* | | `current_solution` | `dict[str, float]` | The currently navigated point. | *required* | | `alpha` | `float` | Step size. Between 0 and 1. | *required* | | `matrix_a` | `ndarray` | The A' matrix. | *required* | | `b` | `ndarray` | The b vector. | *required* | Returns: | Type | Description | | ------------------ | -------------------------------------- | | `dict[str, float]` | dict\[str, float\]: The next solution. | Source code in `desdeo/mcdm/pareto_navigator.py` ``` def calculate_next_solution( problem: Problem, search_direction: dict[str, float], current_solution: dict[str, float], alpha: float, matrix_a: np.ndarray, b: np.ndarray, ) -> dict[str, float]: """Calculate the next solution. Args: problem (Problem): The problem being solved. search_direction (dict[str, float]): The search direction. current_solution (dict[str, float]): The currently navigated point. alpha (float): Step size. Between 0 and 1. matrix_a (np.ndarray): The A' matrix. b (np.ndarray): The b vector. Returns: dict[str, float]: The next solution. """ z = objective_dict_to_numpy_array(problem, current_solution) k = len(z) d = objective_dict_to_numpy_array(problem, search_direction) q = z + alpha * d q = np.reshape(q, ((k, 1))) b_new = np.append(q, b) ideal = objective_dict_to_numpy_array(problem, problem.get_ideal_point()) nadir = objective_dict_to_numpy_array(problem, problem.get_nadir_point()) c = np.array([1] + k * [0]) obj_bounds = np.stack((ideal, nadir)) bounds = [(None, None)] for x, y in obj_bounds.T: bounds.append((x, y)) z_new = linprog(c=c, A_ub=matrix_a, b_ub=b_new, bounds=bounds) if z_new["success"]: return numpy_array_to_objective_dict(problem, z_new["x"][1:]) return current_solution # should raise an exception instead ``` #### calculate_search_direction ``` calculate_search_direction( problem: Problem, reference_point: dict[str, float], current_point: dict[str, float], ) -> dict[str, float] ``` Calculate search direction from the current point to the reference point. Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | -------------------------- | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | | `reference_point` | `dict[str, float]` | The given reference point. | *required* | | `current_point` | `dict[str, float]` | Currently navigated point. | *required* | Returns: | Type | Description | | ------------------ | -------------------------------------------------------------------------------- | | `dict[str, float]` | dict\[str, float\]: The direction from the current point to the reference point. | Source code in `desdeo/mcdm/pareto_navigator.py` ``` def calculate_search_direction( problem: Problem, reference_point: dict[str, float], current_point: dict[str, float] ) -> dict[str, float]: """Calculate search direction from the current point to the reference point. Args: problem (Problem): The problem being solved. reference_point (dict[str, float]): The given reference point. current_point (dict[str, float]): Currently navigated point. Returns: dict[str, float]: The direction from the current point to the reference point. """ z = objective_dict_to_numpy_array(problem, current_point) q = objective_dict_to_numpy_array(problem, reference_point) d = q - z return numpy_array_to_objective_dict(problem, d) ``` #### classification_to_reference_point ``` classification_to_reference_point( problem: Problem, pref_info: dict[str, str], current_solution: dict[str, float], ) -> dict[str, float] ``` Convert preference information given as classification into a reference point. Parameters: | Name | Type | Description | Default | | ------------------ | ------------------ | --------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | | `pref_info` | `dict[str, str]` | The preference information given as classification. | *required* | | `current_solution` | `dict[str, float]` | The current solution. | *required* | Returns: | Type | Description | | ------------------ | -------------------------------------------------------------------- | | `dict[str, float]` | dict\[str, float\]: A reference point converted from classification. | Source code in `desdeo/mcdm/pareto_navigator.py` ``` def classification_to_reference_point( problem: Problem, pref_info: dict[str, str], current_solution: dict[str, float] ) -> dict[str, float]: """Convert preference information given as classification into a reference point. Args: problem (Problem): The problem being solved. pref_info (dict[str, str]): The preference information given as classification. current_solution (dict[str, float]): The current solution. Returns: dict[str, float]: A reference point converted from classification. """ ref = [] ideal = problem.get_ideal_point() nadir = problem.get_nadir_point() for pref, pref_value in pref_info.items(): if pref_value == "<": ref.append(ideal[pref]) elif pref_value == ">": ref.append(nadir[pref]) elif pref_value == "=": ref.append(current_solution[pref]) return numpy_array_to_objective_dict(problem, np.array(ref)) ``` #### construct_matrix_a ``` construct_matrix_a( problem: Problem, matrix_a: ndarray ) -> np.ndarray ``` Construct the A' matrix in the linear parametric programming problem from the article. Parameters: | Name | Type | Description | Default | | ---------- | --------- | ---------------------------------------------- | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | | `matrix_a` | `ndarray` | The A matrix from the polyhedral set equation. | *required* | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: The A' matrix in the linear parametric programming problem from the article. | Source code in `desdeo/mcdm/pareto_navigator.py` ``` def construct_matrix_a(problem: Problem, matrix_a: np.ndarray) -> np.ndarray: """Construct the A' matrix in the linear parametric programming problem from the article. Args: problem (Problem): The problem being solved. matrix_a (np.ndarray): The A matrix from the polyhedral set equation. Returns: np.ndarray: The A' matrix in the linear parametric programming problem from the article. """ ideal = objective_dict_to_numpy_array(problem, problem.get_ideal_point()) nadir = objective_dict_to_numpy_array(problem, problem.get_nadir_point()) weights = 1 / (nadir - ideal) weights_inverse = np.reshape(np.vectorize(lambda w: -1 / w)(weights), (len(weights), 1)) identity = np.identity(len(weights)) a_upper = np.c_[weights_inverse, identity] zeros = np.zeros((len(matrix_a), 1)) a_lower = np.c_[zeros, matrix_a] return np.concatenate((a_upper, a_lower)) ``` #### get_polyhedral_set ``` get_polyhedral_set( problem: Problem, ) -> tuple[np.ndarray, np.ndarray] ``` Get a polyhedral set as convex hull from the set of pareto optimal solutions. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------- | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | Returns: | Type | Description | | ------------------------- | -------------------------------------------------------------------------------------------- | | `tuple[ndarray, ndarray]` | tuple\[np.ndarray, np.ndarray\]: The A matrix and b vector from the polyhedral set equation. | Source code in `desdeo/mcdm/pareto_navigator.py` ``` def get_polyhedral_set(problem: Problem) -> tuple[np.ndarray, np.ndarray]: """Get a polyhedral set as convex hull from the set of pareto optimal solutions. Args: problem (Problem): The problem being solved. Returns: tuple[np.ndarray, np.ndarray]: The A matrix and b vector from the polyhedral set equation. """ objective_values = problem.discrete_representation.objective_values representation = np.array([objective_values[obj.symbol] for obj in problem.objectives]) convex_hull = ConvexHull(representation.T) matrix_a = convex_hull.equations[:, 0:-1] b = -convex_hull.equations[:, -1] return matrix_a, b ``` ### desdeo.mcdm.reference_point_method Functions related to the reference point method. This module contains functions related to the reference point method as presented in Wierzbicki, A. P. (1982). A mathematical basis for satisficing decision making. Mathematical modelling, 3(5), 391-405. #### ReferencePointError Bases: `Exception` Raised when an error with the reference point method is encountered. Source code in `desdeo/mcdm/reference_point_method.py` ``` class ReferencePointError(Exception): """Raised when an error with the reference point method is encountered.""" ``` #### rpm_intermediate_solutions ``` rpm_intermediate_solutions( problem: Problem, solution_1: dict[str, float], solution_2: dict[str, float], num_desired: int, scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[SolverResults] ``` Generates a desired number of intermediate solutions between two given solutions. Generates a desires number of intermediate solutions given reference vectors. The solutions are generated by taking n number of steps between the two reference points in the objective space. The vectors corresponding to these values are then utilized as reference points in the achievement scalarizing function. Solving the functions for each reference point will a solution close the the projection of the reference point on the Pareto optimal front of the problem. These solutions are then returned. Note that the intermediate solutions are generated *between* the two given reference points, this means the returned solutions will not include solutions corresponding to the original reference points. Parameters: | Name | Type | Description | Default | | ----------------------- | ------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `solution_1` | `dict[str, VariableType]` | the first of the reference points between which the intermediate solutions are to be generated. | *required* | | `solution_2` | `dict[str, VariableType]` | the second of the reference points between which the intermediate solutions are to be generated. | *required* | | `num_desired` | `int` | the number of desired intermediate solutions to be generated. Must be at least 1. | *required* | | `scalarization_options` | \`dict | None\` | optional kwargs passed to the scalarization function. Defaults to None. | | `solver` | \`BaseSolver | None\` | solver used to solve the problem. If not given, an appropriate solver will be automatically determined based on the features of problem. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | optional options passed to the solver. Ignored if solver is None. Defaults to None. | Returns: | Type | Description | | --------------------- | ------------------------------------------------------------------------------------------------- | | `list[SolverResults]` | list\[SolverResults\]: a list with the projected intermediate solutions as SolverResults objects. | Source code in `desdeo/mcdm/reference_point_method.py` ``` def rpm_intermediate_solutions( problem: Problem, solution_1: dict[str, float], solution_2: dict[str, float], num_desired: int, scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, ) -> list[SolverResults]: """Generates a desired number of intermediate solutions between two given solutions. Generates a desires number of intermediate solutions given reference vectors. The solutions are generated by taking n number of steps between the two reference points in the objective space. The vectors corresponding to these values are then utilized as reference points in the achievement scalarizing function. Solving the functions for each reference point will a solution close the the projection of the reference point on the Pareto optimal front of the problem. These solutions are then returned. Note that the intermediate solutions are generated _between_ the two given reference points, this means the returned solutions will not include solutions corresponding to the original reference points. Args: problem (Problem): the problem being solved. solution_1 (dict[str, VariableType]): the first of the reference points between which the intermediate solutions are to be generated. solution_2 (dict[str, VariableType]): the second of the reference points between which the intermediate solutions are to be generated. num_desired (int): the number of desired intermediate solutions to be generated. Must be at least `1`. scalarization_options (dict | None, optional): optional kwargs passed to the scalarization function. Defaults to None. solver (BaseSolver | None, optional): solver used to solve the problem. If not given, an appropriate solver will be automatically determined based on the features of `problem`. Defaults to None. solver_options (SolverOptions | None, optional): optional options passed to the `solver`. Ignored if `solver` is `None`. Defaults to None. Returns: list[SolverResults]: a list with the projected intermediate solutions as `SolverResults` objects. """ if int(num_desired) < 1: msg = f"The given number of desired intermediate ({num_desired=}) solutions must be at least 1." raise ReferencePointError(msg) init_solver = guess_best_solver(problem) if solver is None else solver _solver_options = None if solver_options is None or solver is None else solver_options # Find intermediate solutions by dividing the distance between the two Pareto points into num_desired+1 steps, # calculate the solutions found in between the points, because we don't want to find the original solutions intermediate_solutions = [] for i in range(num_desired): rp = { key: ((i + 1) * solution_1[key] + (num_desired - i) * solution_2[key]) / (num_desired + 1) for key in solution_1.keys() # noqa: SIM118 } # add scalarization add_asf = add_asf_diff if problem.is_twice_differentiable else add_asf_nondiff asf_problem, target = add_asf(problem, "target", rp, **(scalarization_options or {})) solver_instance = init_solver(asf_problem, _solver_options) # solve and store results result: SolverResults = solver_instance.solve(target) intermediate_solutions.append(result) return intermediate_solutions ``` #### rpm_solve_solutions ``` rpm_solve_solutions( problem: Problem, reference_point: dict[str, float], scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, *, include_perturbed: bool = True, ) -> list[SolverResults] ``` Finds (near) Pareto optimal solutions based on a reference point. Find a (near) Pareto optimal solution based on the given reference point by optimizing an achievement scalarizing function. The original reference point is also perturbed, and another k (near) Pareto optimal solutions are found. The k+1 solutions are then returned. If `include_perturbed` is `False`, only the solution based on the given reference point is found and returned. Parameters: | Name | Type | Description | Default | | ----------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to be solved. | *required* | | `reference_point` | `dict[str, float]` | the reference point. The keys of the dict represent the objective function symbols defined in problem. The values represent the aspiration level values. | *required* | | `scalarization_options` | \`dict | None\` | keyword arguments to be passed to the achievement scalarizing function. Defaults to None. | | `solver` | \`BaseSolver | None\` | solver to optimize the achievement scalarizing function. If not given, the method tried to guess the most suitable solver based on the problem. Defaults to None. | | `solver_options` | \`SolverOptions | None\` | options passed to the solver. If not given, the solver will use its default options. Defaults to None. | | `include_perturbed` | `bool` | whether to also find the k solutions based on the perturbed reference points. If False, a single solution is returned, which keeps "the current solution" unambiguous. Defaults to True. | `True` | Raises: | Type | Description | | --------------------- | ----------------------------------- | | `ReferencePointError` | the reference point is ill-defined. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `list[SolverResults]` | list\[SolverResults\]: a list of results containing the solution found using the reference point and, if include_perturbed is True, the solutions found using the k perturbed reference points. | Note If the problem is twice differentiable, `add_asf_diff` is used from `desdeo.tools`. If the problem is not twice differentiable, then `add_asf_nondiff` is used. Source code in `desdeo/mcdm/reference_point_method.py` ``` def rpm_solve_solutions( problem: Problem, reference_point: dict[str, float], scalarization_options: dict | None = None, solver: BaseSolver | None = None, solver_options: SolverOptions | None = None, *, include_perturbed: bool = True, ) -> list[SolverResults]: """Finds (near) Pareto optimal solutions based on a reference point. Find a (near) Pareto optimal solution based on the given reference point by optimizing an achievement scalarizing function. The original reference point is also perturbed, and another k (near) Pareto optimal solutions are found. The k+1 solutions are then returned. If `include_perturbed` is `False`, only the solution based on the given reference point is found and returned. Args: problem (Problem): the problem to be solved. reference_point (dict[str, float]): the reference point. The keys of the dict represent the objective function symbols defined in problem. The values represent the aspiration level values. scalarization_options (dict | None, optional): keyword arguments to be passed to the achievement scalarizing function. Defaults to None. solver (BaseSolver | None, optional): solver to optimize the achievement scalarizing function. If not given, the method tried to guess the most suitable solver based on the problem. Defaults to None. solver_options (SolverOptions | None, optional): options passed to the solver. If not given, the solver will use its default options. Defaults to None. include_perturbed (bool, optional): whether to also find the k solutions based on the perturbed reference points. If `False`, a single solution is returned, which keeps "the current solution" unambiguous. Defaults to True. Raises: ReferencePointError: the reference point is ill-defined. Returns: list[SolverResults]: a list of results containing the solution found using the reference point and, if `include_perturbed` is `True`, the solutions found using the k perturbed reference points. Note: If the problem is twice differentiable, `add_asf_diff` is used from `desdeo.tools`. If the problem is not twice differentiable, then `add_asf_nondiff` is used. """ # setup problem with ASF # check if problem is differentiable or not, choose appropriate ASF variant. if not all(obj.symbol in reference_point for obj in problem.objectives): msg = f"The reference point {reference_point} is missing entries for one or more of the objective functions." raise ReferencePointError(msg) _add_asf = add_asf_diff if problem.is_twice_differentiable else add_asf_nondiff problem_w_asf, target = _add_asf( problem, "_asf", reference_point, **scalarization_options if scalarization_options is not None else {} ) # setup solver # solve scalarized problem with given reference point _init_solver = guess_best_solver(problem_w_asf) if solver is None else solver _solver = _init_solver(problem_w_asf, solver_options) initial_solution = _solver.solve(target) if not include_perturbed: return [initial_solution] # using the found solution, perturb the reference point to get # k (num of objectives) perturbed reference points initial_objective_vector = objective_dict_to_numpy_array(problem, initial_solution.optimal_objectives) reference_point_vector = objective_dict_to_numpy_array(problem, reference_point) distance = np.linalg.norm(reference_point_vector - initial_objective_vector) unit_vectors = np.eye(len(initial_objective_vector)) perturbed_reference_point_vectors = reference_point_vector + (distance * unit_vectors) perturbed_reference_points = [numpy_array_to_objective_dict(problem, v) for v in perturbed_reference_point_vectors] # scalarize the problem using the appropriate ASF variant and the perturbed # reference points perturbed_problems_and_targets = [ _add_asf(problem, "_asf", rp, **scalarization_options if scalarization_options is not None else {}) for rp in perturbed_reference_points ] # solve the problems perturbed_solutions = [ _init_solver(problem_and_target[0], solver_options).solve(problem_and_target[1]) for problem_and_target in perturbed_problems_and_targets ] # return the original solution and the solutions found with the perturbed reference points return [initial_solution, *perturbed_solutions] ``` ## Test problems Pre-defined multiobjective optimization problems. Pre-defined problems for, e.g., testing and illustration purposed are defined here. ### best_cake_problem ``` best_cake_problem() -> Problem ``` Defines the best cake problem. Source code in `desdeo/problem/testproblems/cake_problem.py` ``` def best_cake_problem() -> Problem: """Defines the best cake problem.""" variable_inits = [ ("Flour", 0.70), ("Sugar", 0.10), ("Butter", 0.40), ("Eggs", 0.50), ("Milk", 0.20), ("Baking powder", 0.80), ] variables = [ Variable( name=var[0], symbol=f"x{i + 1}", variable_type=VariableTypeEnum.real, lowerbound=0.0, upperbound=1.0, initial_value=var[1], ) for i, var in enumerate(variable_inits) ] constants_init = [ ("T1", 0.60), ("T2", 0.35), ("T3", 0.25), ("T4", 0.30), ("T5", 0.35), ("T6", 0.40), ("INV_D1", 1.0 / 0.60), ("INV_D2", 1.0 / 0.65), ("INV_D3", 1.0 / 0.75), ("INV_D4", 1.0 / 0.70), ("INV_D5", 1.0 / 0.65), ("INV_D6", 1.0 / 0.60), ("Y_LIQ_STAR", 0.5 * 0.35 + 0.3 * 0.30 + 0.2 * 0.25), ("INV_D_YLIQ", 1.0 / 0.685), ("SBAR_STAR", (0.35 + 0.5 * 0.25) / 1.5), ("W25_STAR", U(0.35) * U(0.35)), ("INV_DW25", 1.0 / 0.8281), ("W35_STAR", U(0.25) * U(0.35)), ("INV_DW35", 1.0 / 0.6825), ] constants = [Constant(name=const[0], symbol=const[0], value=const[1]) for const in constants_init] objectives = [ Objective( name="Dry/crumb error", symbol="dry_crumb", func=f0_str(), ideal=0.0, nadir=14.0, objective_type=ObjectiveTypeEnum.analytical, is_twice_differentiable=True, # right? ), Objective( name="Sweetness/texture off-target", symbol="sweet_texture", func=f1_str(), ideal=0.0, nadir=14.0, objective_type=ObjectiveTypeEnum.analytical, is_twice_differentiable=True, ), Objective( name="Rise/collapse risk", symbol="rise_collapse", func=f2_str(), ideal=0.0, nadir=14.0, objective_type=ObjectiveTypeEnum.analytical, is_twice_differentiable=True, ), Objective( name="Moistness/grease imbalance", symbol="moistness_grease", func=f3_str(), ideal=0.0, nadir=14.0, objective_type=ObjectiveTypeEnum.analytical, is_twice_differentiable=True, ), Objective( name="Browning/burn risk", symbol="browning_burn", func=f4_str(), ideal=0.0, nadir=14.0, objective_type=ObjectiveTypeEnum.analytical, is_twice_differentiable=True, ), ] return Problem( name="Cake problem", description="Try to find the most delicious cake!", constants=constants, variables=variables, objectives=objectives, ) ``` ### binh_and_korn ``` binh_and_korn( maximize: tuple[bool] = (False, False), ) -> Problem ``` Create the pydantic dataclass representation of the Binh and Korn problem. The function has two objective functions, two variables, and two constraint functions. For testing purposes, it can be chosen whether the firs and second objective should be maximized instead. Parameters: | Name | Type | Description | Default | | ---------- | ------------- | --------------------------------------------------------------------------------------------- | ---------------- | | `maximize` | `tuple[bool]` | whether the first or second objective should be maximized or not. Defaults to (False, False). | `(False, False)` | Returns: | Name | Type | Description | | --------- | --------- | ---------------------------------------------------------- | | `Problem` | `Problem` | A problem instance representing the Binh and Korn problem. | References Binh T. and Korn U. (1997) MOBES: A Multiobjective Evolution Strategy for Constrained Optimization Problems. In: Proceedings of the Third International Conference on Genetic Algorithms. Czech Republic. pp. 176-182. Source code in `desdeo/problem/testproblems/binh_and_korn_problem.py` ``` def binh_and_korn(maximize: tuple[bool] = (False, False)) -> Problem: """Create the pydantic dataclass representation of the Binh and Korn problem. The function has two objective functions, two variables, and two constraint functions. For testing purposes, it can be chosen whether the firs and second objective should be maximized instead. Arguments: maximize (tuple[bool]): whether the first or second objective should be maximized or not. Defaults to (False, False). Returns: Problem: A problem instance representing the Binh and Korn problem. References: Binh T. and Korn U. (1997) MOBES: A Multiobjective Evolution Strategy for Constrained Optimization Problems. In: Proceedings of the Third International Conference on Genetic Algorithms. Czech Republic. pp. 176-182. """ # These constants are for demonstrative purposes. constant_1 = Constant(name="Four", symbol="c_1", value=4) constant_2 = Constant(name="Five", symbol="c_2", value=5) variable_1 = Variable( name="The first variable", symbol="x_1", variable_type="real", lowerbound=0, upperbound=5, initial_value=2.5 ) variable_2 = Variable( name="The second variable", symbol="x_2", variable_type="real", lowerbound=0, upperbound=3, initial_value=1.5 ) objective_1 = Objective( name="Objective 1", symbol="f_1", func=f"{'-' if maximize[0] else ''}(c_1 * x_1**2 + c_1*x_2**2)", # func=["Add", ["Multiply", "c_1", ["Square", "x_1"]], ["Multiply", "c_1", ["Square", "x_2"]]], maximize=maximize[0], ideal=0, nadir=140 if not maximize[0] else -140, is_linear=False, is_convex=True, is_twice_differentiable=True, ) objective_2 = Objective( name="Objective 2", symbol="f_2", # func=["Add", ["Square", ["Subtract", "x_1", "c_2"]], ["Square", ["Subtract", "x_2", "c_2"]]], func=f"{'-' if maximize[1] else ''}((x_1 - c_2)**2 + (x_2 - c_2)**2)", maximize=maximize[1], ideal=0, nadir=50 if not maximize[0] else -50, is_linear=False, is_convex=True, is_twice_differentiable=True, ) constraint_1 = Constraint( name="Constraint 1", symbol="g_1", cons_type="<=", func=["Add", ["Square", ["Subtract", "x_1", "c_2"]], ["Square", "x_2"], -25], is_linear=False, is_convex=True, is_twice_differentiable=True, ) constraint_2 = Constraint( name="Constraint 2", symbol="g_2", cons_type="<=", func=["Add", ["Negate", ["Square", ["Subtract", "x_1", 8]]], ["Negate", ["Square", ["Add", "x_2", 3]]], 7.7], is_linear=False, is_convex=True, is_twice_differentiable=True, ) return Problem( name="The Binh and Korn function", description="The two-objective problem used in the paper by Binh and Korn.", constants=[constant_1, constant_2], variables=[variable_1, variable_2], objectives=[objective_1, objective_2], constraints=[constraint_1, constraint_2], is_twice_differentiable=True, ) ``` ### car_side_impact ``` car_side_impact(three_obj: bool = True) -> Problem ``` The Car-side impact problem with two possible version of the problem with three or four objectives. The constraints and objective functions for the car side-impact problem are defined as follows: \[\\begin{align} \\min\\quad f_1(\\mathbf{x}) &= 1.98 + 4.9x_1 + 6.67x_2 + 6.98x_3 + 4.01x_4 - 1.78x_5 + 0.00001x_6 + 2.73x_7 \\ \\min\\quad f_2(\\mathbf{x}) &= 4.72 - 0.5x_4 - 0.19x_2x_3 \\ \\min\\quad f_3(\\mathbf{x}) &= 0.5,(V\_{MBP} + V\_{FD}) \\ \\min\\quad f_4(\\mathbf{x}) &= \\max(1.16 - 0.3717x_2x_4 - 0.0092928x_3 - 1.0, 0) \\ &+ \\max(0.261 - 0.0159x_1x_2 - 0.06486x_1 - 0.019x_2x_7 - 0.0144x_3x_5 + 0.0154464x_6 - 0.32, 0) \\ &+ \\max(0.214 + 0.00817x_5 - 0.045195x_1 - 0.0135168x_1 + 0.03099x_2x_6 - 0.018x_2x_7 - 0.007176x_3 + 0.023232x_3 - 0.00364x_5x_6 - 0.018x_2^2 - 0.32, 0) \\ &+ \\max(0.74 - 0.61x_2 - 0.031296x_3 - 0.031872x_7 + 0.227x_2^2 - 0.32,0) \\ &+ \\max(28.98 + 3.818x_3 - 4.2x_1x_2 + 1.27296x_6 - 2.68065x_7 - 32.0,0) \\ &+ \\max(33.86 + 2.95x_3 - 5.057x_1x_2 - 3.795x_2 - 3.4431x_7 + 1.45728 - 32.0,0) \\ &+ \\max(46.36 - 9.9x_2 - 4.4505x_1 - 32.0,0) \\ &+ \\max(4.72 - 0.5x_4 - 0.19x_2x_3 - 4.0, 0) \\ &+ \\max(10.58 - 0.674x_1x_2 - 0.67275x_2 - 9.9, 0) \\ &+ \\max(16.45 - 0.489x_3x_7 - 0.843x_5x_6 - 15.7, 0) \\ g_1(\\mathbf{x}) &= 1.16 - 0.3717x_2x_4 - 0.0092928x_3 \\leq 1.0 \\ g_2(\\mathbf{x}) &= 0.261 - 0.0159x_1x_2 - 0.06486x_1 * 0.019x_2x_7 + 0.0144x_3x_5 - 0.0154464x_6 \\leq 0.32 \\ g_3(\\mathbf{x}) &= 0.214 + 0.00817x_5 - 0.045195x_1 * 0.0135168x_1 + 0.03099x_2x_6 * 0.018x_2x_7 + 0.007176x_3 - 0.023232x_3 - 0.00364x_5x_6 * 0.018x_2^2 \\leq 0.32 \\ g_4(\\mathbf{x}) &= 0.74 - 0.61x_2 - 0.031296x_3 * 0.031872x_7 + 0.227x_2^2 \\leq 0.32 \\ g_5(\\mathbf{x}) &= 28.98 + 3.818x_3 * 4.2x_1x_2 - 1.27296x_6 * 2.68065x_7 \\leq 32.0 \\ g_6(\\mathbf{x}) &= 33.86 + 2.95x_3 * 5.057x_1x_2 * 3.795x_2 * 3.4431x_7 - 1.45728 \\leq 32.0 \\ g_7(\\mathbf{x}) &= 46.36 - 9.9x_2 - 4.4505x_1 \\leq 32.0 \\ g_8(\\mathbf{x}) &= 4.72 - 0.5x_4 - 0.19x_2x_3 \\leq 4.0 \\ g_9(\\mathbf{x}) &= 10.58 - 0.674x_1x_2 - 0.67275x_2 \\leq 9.9 \\ g\_{10}(\\mathbf{x}) &= 16.45 - 0.489x_3x_7 - 0.843x_5x_6 \\leq 15.7 \\ &\\mathbf{x}^{L} \\leq \\mathbf{x} \\leq \\mathbf{x}^{U}, \\end{align}\] where [ V\_{MBP} = 10.58 - 0.674x_1x_2 - 0.67275x_2, ] [ V\_{FD} = 16.45 - 0.489x_3x_7 - 0.843x_5x_6, ] [ \\mathbf{x}^{L} = (0.5,,0.45,,0.5,,0.5,,0.875,,0.4,,0.4), ] [ \\mathbf{x}^{U} = (1.5,,1.35,,1.5,,1.5,,2.625,,1.2,,1.2). ] Parameters: | Name | Type | Description | Default | | ----------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `three_obj` | `bool` | If true, utilize the three objectives version (objectives (f_1)-(f_3)). If false, utilizes the fourth objective ((f_4)) as well. Defaults to true (three objectives). | `True` | Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------------------ | | `Problem` | `Problem` | A problem instance representing the Car-side impact problem. | References Jain, H., & Deb, K. (2014). An evolutionary many-objective optimization algorithm using reference-point based nondominated sorting approach, part II. IEEE TEVC, 18(4), 602-622. Three objective problem from: Jain, H. & Deb, K. (2014). An Evolutionary Many-Objective Optimization Algorithm Using Reference-Point Based Nondominated Sorting Approach, Part II: Handling Constraints and Extending to an Adaptive Approach. IEEE transactions on evolutionary computation, 18(4), 602-622. Optional fourth objective from: Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. Variable names from: Deb, K., Gupta, S., Daum, D., Branke, J., Mall, A. & Padmanabhan, D. (2009). Reliability-Based Optimization Using Evolutionary Algorithms. IEEE transactions on evolutionary computation, 13(5), 1054-1074. Source code in `desdeo/problem/testproblems/car_side_impact_problem.py` ``` def car_side_impact(three_obj: bool = True) -> Problem: r"""The Car-side impact problem with two possible version of the problem with three or four objectives. The constraints and objective functions for the car side-impact problem are defined as follows: \begin{align} \min\quad f_1(\mathbf{x}) &= 1.98 + 4.9x_1 + 6.67x_2 + 6.98x_3 + 4.01x_4 + 1.78x_5 + 0.00001x_6 + 2.73x_7 \\ \min\quad f_2(\mathbf{x}) &= 4.72 - 0.5x_4 - 0.19x_2x_3 \\ \min\quad f_3(\mathbf{x}) &= 0.5\,(V_{MBP} + V_{FD}) \\ \min\quad f_4(\mathbf{x}) &= \max(1.16 - 0.3717x_2x_4 - 0.0092928x_3 - 1.0, 0) \\ &+ \max(0.261 - 0.0159x_1x_2 - 0.06486x_1 - 0.019x_2x_7 + 0.0144x_3x_5 + 0.0154464x_6 - 0.32, 0) \\ &+ \max(0.214 + 0.00817x_5 - 0.045195x_1 - 0.0135168x_1 + 0.03099x_2x_6 - 0.018x_2x_7 + 0.007176x_3 + 0.023232x_3 - 0.00364x_5x_6 - 0.018x_2^2 - 0.32, 0) \\ &+ \max(0.74 - 0.61x_2 - 0.031296x_3 - 0.031872x_7 + 0.227x_2^2 - 0.32,0) \\ &+ \max(28.98 + 3.818x_3 - 4.2x_1x_2 + 1.27296x_6 - 2.68065x_7 - 32.0,0) \\ &+ \max(33.86 + 2.95x_3 - 5.057x_1x_2 - 3.795x_2 - 3.4431x_7 + 1.45728 - 32.0,0) \\ &+ \max(46.36 - 9.9x_2 - 4.4505x_1 - 32.0,0) \\ &+ \max(4.72 - 0.5x_4 - 0.19x_2x_3 - 4.0, 0) \\ &+ \max(10.58 - 0.674x_1x_2 - 0.67275x_2 - 9.9, 0) \\ &+ \max(16.45 - 0.489x_3x_7 - 0.843x_5x_6 - 15.7, 0) \\ g_1(\mathbf{x}) &= 1.16 - 0.3717x_2x_4 - 0.0092928x_3 \leq 1.0 \\ g_2(\mathbf{x}) &= 0.261 - 0.0159x_1x_2 - 0.06486x_1 - 0.019x_2x_7 + 0.0144x_3x_5 + 0.0154464x_6 \leq 0.32 \\ g_3(\mathbf{x}) &= 0.214 + 0.00817x_5 - 0.045195x_1 - 0.0135168x_1 + 0.03099x_2x_6 - 0.018x_2x_7 + 0.007176x_3 + 0.023232x_3 - 0.00364x_5x_6 - 0.018x_2^2 \leq 0.32 \\ g_4(\mathbf{x}) &= 0.74 - 0.61x_2 - 0.031296x_3 - 0.031872x_7 + 0.227x_2^2 \leq 0.32 \\ g_5(\mathbf{x}) &= 28.98 + 3.818x_3 - 4.2x_1x_2 + 1.27296x_6 - 2.68065x_7 \leq 32.0 \\ g_6(\mathbf{x}) &= 33.86 + 2.95x_3 - 5.057x_1x_2 - 3.795x_2 - 3.4431x_7 + 1.45728 \leq 32.0 \\ g_7(\mathbf{x}) &= 46.36 - 9.9x_2 - 4.4505x_1 \leq 32.0 \\ g_8(\mathbf{x}) &= 4.72 - 0.5x_4 - 0.19x_2x_3 \leq 4.0 \\ g_9(\mathbf{x}) &= 10.58 - 0.674x_1x_2 - 0.67275x_2 \leq 9.9 \\ g_{10}(\mathbf{x}) &= 16.45 - 0.489x_3x_7 - 0.843x_5x_6 \leq 15.7 \\ &\mathbf{x}^{L} \leq \mathbf{x} \leq \mathbf{x}^{U}, \end{align} where \[ V_{MBP} = 10.58 - 0.674x_1x_2 - 0.67275x_2, \] \[ V_{FD} = 16.45 - 0.489x_3x_7 - 0.843x_5x_6, \] \[ \mathbf{x}^{L} = (0.5,\,0.45,\,0.5,\,0.5,\,0.875,\,0.4,\,0.4), \] \[ \mathbf{x}^{U} = (1.5,\,1.35,\,1.5,\,1.5,\,2.625,\,1.2,\,1.2). \] Arguments: three_obj (bool): If true, utilize the three objectives version (objectives $f_1$-$f_3$). If false, utilizes the fourth objective ($f_4$) as well. Defaults to true (three objectives). Returns: Problem: A problem instance representing the Car-side impact problem. References: Jain, H., & Deb, K. (2014). An evolutionary many-objective optimization algorithm using reference-point based nondominated sorting approach, part II. IEEE TEVC, 18(4), 602-622. Three objective problem from: Jain, H. & Deb, K. (2014). An Evolutionary Many-Objective Optimization Algorithm Using Reference-Point Based Nondominated Sorting Approach, Part II: Handling Constraints and Extending to an Adaptive Approach. IEEE transactions on evolutionary computation, 18(4), 602-622. Optional fourth objective from: Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. Variable names from: Deb, K., Gupta, S., Daum, D., Branke, J., Mall, A. & Padmanabhan, D. (2009). Reliability-Based Optimization Using Evolutionary Algorithms. IEEE transactions on evolutionary computation, 13(5), 1054-1074. """ x_1 = Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.5, upperbound=1.5, ) x_2 = Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.45, upperbound=1.35, ) x_3 = Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0.5, upperbound=1.5, ) x_4 = Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=0.5, upperbound=1.5, ) x_5 = Variable( name="x_5", symbol="x_5", variable_type=VariableTypeEnum.real, lowerbound=0.875, upperbound=2.625, ) x_6 = Variable( name="x_6", symbol="x_6", variable_type=VariableTypeEnum.real, lowerbound=0.4, upperbound=1.2, ) x_7 = Variable( name="x_7", symbol="x_7", variable_type=VariableTypeEnum.real, lowerbound=0.4, upperbound=1.2, ) g_1 = Constraint( name="g_1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func="1.16 - 0.3717 * x_2 * x_4 - 0.0092928 * x_3 - 1.0", is_linear=False, is_convex=False, is_twice_differentiable=True, ) g_2 = Constraint( name="g_2", symbol="g_2", cons_type=ConstraintTypeEnum.LTE, func=( "0.261" " - 0.0159 * x_1 * x_2" " - 0.06486 * x_1" " - 0.019 * x_2 * x_7" " + 0.0144 * x_3 * x_5" " + 0.0154464 * x_6" " - 0.32" ), is_linear=False, is_convex=False, is_twice_differentiable=True, ) g_3 = Constraint( name="g_3", symbol="g_3", cons_type=ConstraintTypeEnum.LTE, func=( "0.214" " + 0.00817 * x_5" " - 0.045195 * x_1" " - 0.0135168 * x_1" " + 0.03099 * x_2 * x_6" " - 0.018 * x_2 * x_7" " + 0.007176 * x_3" " + 0.023232 * x_3" " - 0.00364 * x_5 * x_6" " - 0.018 * x_2**2" " - 0.32" ), is_linear=False, is_convex=False, is_twice_differentiable=True, ) g_4 = Constraint( name="g_4", symbol="g_4", cons_type=ConstraintTypeEnum.LTE, func="0.74 - 0.61 * x_2 - 0.031296 * x_3 - 0.031872 * x_7 + 0.227 * x_2**2 - 0.32", is_linear=False, is_convex=False, is_twice_differentiable=True, ) g_5 = Constraint( name="g_5", symbol="g_5", cons_type=ConstraintTypeEnum.LTE, func="28.98 + 3.818 * x_3 - 4.2 * x_1 * x_2 + 1.27296 * x_6 - 2.68065 * x_7 - 32.0", is_linear=False, is_convex=False, is_twice_differentiable=True, ) g_6 = Constraint( name="g_6", symbol="g_6", cons_type=ConstraintTypeEnum.LTE, func="33.86 + 2.95 * x_3 - 5.057 * x_1 * x_2 - 3.795 * x_2 - 3.4431 * x_7 + 1.45728 - 32.0", is_linear=False, is_convex=False, is_twice_differentiable=True, ) g_7 = Constraint( name="g_7", symbol="g_7", cons_type=ConstraintTypeEnum.LTE, func="46.36 - 9.9 * x_2 - 4.4505 * x_1 - 32.0", is_linear=False, is_convex=False, is_twice_differentiable=True, ) g_8 = Constraint( name="g_8", symbol="g_8", cons_type=ConstraintTypeEnum.LTE, func="4.72 - 0.5 * x_4 - 0.19 * x_2 * x_3 - 4.0", is_linear=False, is_convex=False, is_twice_differentiable=True, ) g_9 = Constraint( name="g_9", symbol="g_9", cons_type=ConstraintTypeEnum.LTE, func="10.58 - 0.674 * x_1 * x_2 - 0.67275 * x_2 - 9.9", is_linear=False, is_convex=False, is_twice_differentiable=True, ) g_10 = Constraint( name="g_10", symbol="g_10", cons_type=ConstraintTypeEnum.LTE, func="16.45 - 0.489 * x_3 * x_7 - 0.843 * x_5 * x_6 - 15.7", is_linear=False, is_convex=False, is_twice_differentiable=True, ) f_1 = Objective( name="f_1", symbol="f_1", func="1.98 + 4.9 * x_1 + 6.67 * x_2 + 6.98 * x_3 + 4.01 * x_4 + 1.78 * x_5 + 0.00001 * x_6 + 2.73 * x_7", objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func="4.72 - 0.5 * x_4 - 0.19 * x_2 * x_3", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, is_twice_differentiable=True, ) f_3 = Objective( name="f_3", symbol="f_3", func="0.5 * ((10.58 - 0.674 * x_1 * x_2 - 0.67275 * x_2) + (16.45 - 0.489 * x_3 * x_7 - 0.843 * x_5 * x_6))", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, is_twice_differentiable=True, ) if three_obj: objectives = [f_1, f_2, f_3] else: # If three_obj is false, then problem is with 4 objectives. f_4 = Objective( name="f_4", symbol="f_4", func=( "Max(1.16 - 0.3717 * x_2 * x_4 - 0.0092928 * x_3 - 1.0, 0)" " + Max(0.261 - 0.0159 * x_1 * x_2 - 0.06486 * x_1 - 0.019 * x_2 * x_7" " + 0.0144 * x_3 * x_5 + 0.0154464 * x_6 - 0.32, 0)" " + Max(0.214 + 0.00817 * x_5 - 0.045195 * x_1 - 0.0135168 * x_1 + 0.03099 * x_2 * x_6" " - 0.018 * x_2 * x_7 + 0.007176 * x_3 + 0.023232 * x_3 - 0.00364 * x_5 * x_6" " - 0.018 * x_2**2 - 0.32, 0)" " + Max(0.74 - 0.61 * x_2 - 0.031296 * x_3 - 0.031872 * x_7 + 0.227 * x_2**2 - 0.32, 0)" " + Max(28.98 + 3.818 * x_3 - 4.2*x_1 * x_2 + 1.27296 * x_6 - 2.68065 * x_7 - 32.0, 0)" " + Max(33.86 + 2.95 * x_3 - 5.057 * x_1 * x_2 - 3.795 * x_2 - 3.4431 * x_7" " + 1.45728 - 32.0, 0)" " + Max(46.36 - 9.9 * x_2 - 4.4505 * x_1 - 32.0, 0)" " + Max(4.72 - 0.5 * x_4 - 0.19 * x_2 * x_3 - 4.0, 0)" " + Max(10.58 - 0.674 * x_1 * x_2 - 0.67275 * x_2 - 9.9, 0)" " + Max(16.45 - 0.489 * x_3 * x_7 - 0.843 * x_5 * x_6 - 15.7, 0)" ), objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, is_twice_differentiable=False, ) objectives = [f_1, f_2, f_3, f_4] return Problem( name="The car-side impact", description="The car-side impact problem", variables=[x_1, x_2, x_3, x_4, x_5, x_6, x_7], objectives=objectives, constraints=[g_1, g_2, g_3, g_4, g_5, g_6, g_7, g_8, g_9, g_10], ) ``` ### ctp1 ``` ctp1(n_variables: int) -> Problem ``` Defines the CTP1 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: \[\\begin{align\*} \\min\\quad f_1(\\textbf{x}) &= x_1 \\[1ex] \\min\\quad f_2(\\textbf{x}) &= g(\\textbf{x}) \\exp!\\left( -\\frac{f_1(\\textbf{x})}{g(\\textbf{x})} \\right) \\[1ex] g(\\textbf{x}) &= 1 + \\frac{9}{n-1}\\sum\_{i=2}^{n} x_i \\[1ex] g_1(\\mathbf{x}) &= 0.858,\\exp(-0.541,x_1) - f_2(\\textbf{x}) \\le 0 \\[1ex] g_2(\\mathbf{x}) &= 0.728,\\exp(-0.295,x_1) - f_2(\\textbf{x}) \\le 0 \\[1ex] 0 &\\le x_i \\le 1, \\qquad i = 1,\\ldots,n. \\end{align\*}\] where (f_1) and (f_2) are objective functions, (x_1,\\dots,x_n) are decision variable, (n) is the number of decision variables, and (g_1) and (g_2) are auxiliary functions. Source code in `desdeo/problem/testproblems/ctp_problems.py` ``` def ctp1(n_variables: int) -> Problem: r"""Defines the CTP1 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: \begin{align*} \min\quad f_1(\textbf{x}) &= x_1 \\[1ex] \min\quad f_2(\textbf{x}) &= g(\textbf{x}) \exp\!\left( -\frac{f_1(\textbf{x})}{g(\textbf{x})} \right) \\[1ex] g(\textbf{x}) &= 1 + \frac{9}{n-1}\sum_{i=2}^{n} x_i \\[1ex] g_1(\mathbf{x}) &= 0.858\,\exp(-0.541\,x_1) - f_2(\textbf{x}) \le 0 \\[1ex] g_2(\mathbf{x}) &= 0.728\,\exp(-0.295\,x_1) - f_2(\textbf{x}) \le 0 \\[1ex] 0 &\le x_i \le 1, \qquad i = 1,\ldots,n. \end{align*} where $f_1$ and $f_2$ are objective functions, $x_1,\dots,x_n$ are decision variable, $n$ is the number of decision variables, and $g_1$ and $g_2$ are auxiliary functions. """ n = n_variables # function f_1 f1_expr = "x_1" # function g g_expr_1 = f"1 + (9 / ({n} - 1))" g_expr_2 = "(" + " + ".join([f"x_{i}" for i in range(2, n + 1)]) + ")" g_expr = g_expr_1 + " * " + g_expr_2 # function f_2 f_2_expr = f"{g_expr} * Exp(-{f1_expr} / ({g_expr}))" variables = [ Variable( name=f"x_{i}", symbol=f"x_{i}", variable_type=VariableTypeEnum.real, lowerbound=0.0, upperbound=1.0, ) for i in range(1, n_variables + 1) ] objective_1 = Objective( name="f_1", symbol="f_1", func="x_1", objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ) objective_2 = Objective( name="f_2", symbol="f_2", func=f_2_expr, objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, is_twice_differentiable=True, ) constraint_1 = Constraint( name="g_1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func=f"0.858 * Exp(-0.541 * x_1) - ({f_2_expr})", is_linear=False, is_convex=False, is_twice_differentiable=True, ) constraint_2 = Constraint( name="g_2", symbol="g_2", cons_type=ConstraintTypeEnum.LTE, func=f"0.728 * Exp(-0.295 * x_1) - ({f_2_expr})", is_linear=False, is_convex=False, is_twice_differentiable=True, ) return Problem( name="ctp1", description="The CTP1 test problem.", variables=variables, objectives=[objective_1, objective_2], constraints=[constraint_1, constraint_2], is_convex=True, is_linear=False, is_twice_differentiable=True, ) ``` ### ctp2 ``` ctp2(n_variables: int) -> Problem ``` Defines the CTP2 test problem. A variable number of decision variables and two objective functions to be minimized: \[\\begin{align\*} \\min\\quad f_1(\\mathbf{x}) &= x_1 \\[1ex] \\min\\quad f_2(\\mathbf{x}) &= g(\\mathbf{x})\\left(1 - \\frac{f_1(\\mathbf{x})}{g(\\mathbf{x})}\\right) \\[1ex] g(\\mathbf{x}) &= 1 + \\frac{9}{n - 1}\\sum\_{i=2}^{n} x_i \\[1ex] \\text{s.t.}\\quad &\\cos(\\theta)(f_2 - e) - \\sin(\\theta) f_1 \\ge a\\left|\\sin!\\big(b\\pi(\\sin(\\theta)(f_2 - e) + \\cos(\\theta) f_1)^c\\big)\\right|^d \\[1ex] &0 \\le x_i \\le 1, \\qquad i = 1,\\ldots,n, \\end{align\*}\] with parameters (\\theta = -0.2\\pi), (a = 0.2), (b = 10), (c = 1), (d = 6), (e = 1). The single constraint makes the unconstrained Pareto front infeasible except in a number of disconnected regions. The g function is not specified in the original chapter; the ZDT-style g above is used for consistency across the DESDEO CTP suite. Source code in `desdeo/problem/testproblems/ctp_problems.py` ``` def ctp2(n_variables: int) -> Problem: r"""Defines the CTP2 test problem. A variable number of decision variables and two objective functions to be minimized: \begin{align*} \min\quad f_1(\mathbf{x}) &= x_1 \\[1ex] \min\quad f_2(\mathbf{x}) &= g(\mathbf{x})\left(1 - \frac{f_1(\mathbf{x})}{g(\mathbf{x})}\right) \\[1ex] g(\mathbf{x}) &= 1 + \frac{9}{n - 1}\sum_{i=2}^{n} x_i \\[1ex] \text{s.t.}\quad &\cos(\theta)(f_2 - e) - \sin(\theta) f_1 \ge a\left|\sin\!\big(b\pi(\sin(\theta)(f_2 - e) + \cos(\theta) f_1)^c\big)\right|^d \\[1ex] &0 \le x_i \le 1, \qquad i = 1,\ldots,n, \end{align*} with parameters $\theta = -0.2\pi$, $a = 0.2$, $b = 10$, $c = 1$, $d = 6$, $e = 1$. The single constraint makes the unconstrained Pareto front infeasible except in a number of disconnected regions. The g function is not specified in the original chapter; the ZDT-style g above is used for consistency across the DESDEO CTP suite. """ return _ctp_problem( name="ctp2", description="The CTP2 test problem.", n_variables=n_variables, constraint_params=[(-0.2 * math.pi, 0.2, 10.0, 1.0, 6.0, 1.0)], ) ``` ### ctp3 ``` ctp3(n_variables: int) -> Problem ``` Defines the CTP3 test problem. Same structure as :func:`ctp2` but with constraint parameters (\\theta = -0.2\\pi), (a = 0.1), (b = 10), (c = 1), (d = 0.5), (e = 1). The smaller (d) shrinks each disconnected feasible region so that each one degenerates towards a single Pareto-optimal solution. Source code in `desdeo/problem/testproblems/ctp_problems.py` ``` def ctp3(n_variables: int) -> Problem: r"""Defines the CTP3 test problem. Same structure as :func:`ctp2` but with constraint parameters $\theta = -0.2\pi$, $a = 0.1$, $b = 10$, $c = 1$, $d = 0.5$, $e = 1$. The smaller $d$ shrinks each disconnected feasible region so that each one degenerates towards a single Pareto-optimal solution. """ return _ctp_problem( name="ctp3", description="The CTP3 test problem.", n_variables=n_variables, constraint_params=[(-0.2 * math.pi, 0.1, 10.0, 1.0, 0.5, 1.0)], ) ``` ### ctp4 ``` ctp4(n_variables: int) -> Problem ``` Defines the CTP4 test problem. Same structure as :func:`ctp2` but with constraint parameters (\\theta = -0.2\\pi), (a = 0.75), (b = 10), (c = 1), (d = 0.5), (e = 1). The larger (a) stretches the infeasible "tunnels" far away from the Pareto-optimal region, making it the hardest of the front-difficulty CTP problems. Source code in `desdeo/problem/testproblems/ctp_problems.py` ``` def ctp4(n_variables: int) -> Problem: r"""Defines the CTP4 test problem. Same structure as :func:`ctp2` but with constraint parameters $\theta = -0.2\pi$, $a = 0.75$, $b = 10$, $c = 1$, $d = 0.5$, $e = 1$. The larger $a$ stretches the infeasible "tunnels" far away from the Pareto-optimal region, making it the hardest of the front-difficulty CTP problems. """ return _ctp_problem( name="ctp4", description="The CTP4 test problem.", n_variables=n_variables, constraint_params=[(-0.2 * math.pi, 0.75, 10.0, 1.0, 0.5, 1.0)], ) ``` ### ctp5 ``` ctp5(n_variables: int) -> Problem ``` Defines the CTP5 test problem. Same structure as :func:`ctp2` but with constraint parameters (\\theta = -0.2\\pi), (a = 0.1), (b = 10), (c = 2), (d = 0.5), (e = 1). With (c \\ne 1) the discrete Pareto-optimal solutions are scattered non-uniformly along the front. Source code in `desdeo/problem/testproblems/ctp_problems.py` ``` def ctp5(n_variables: int) -> Problem: r"""Defines the CTP5 test problem. Same structure as :func:`ctp2` but with constraint parameters $\theta = -0.2\pi$, $a = 0.1$, $b = 10$, $c = 2$, $d = 0.5$, $e = 1$. With $c \ne 1$ the discrete Pareto-optimal solutions are scattered non-uniformly along the front. """ return _ctp_problem( name="ctp5", description="The CTP5 test problem.", n_variables=n_variables, constraint_params=[(-0.2 * math.pi, 0.1, 10.0, 2.0, 0.5, 1.0)], ) ``` ### ctp6 ``` ctp6(n_variables: int) -> Problem ``` Defines the CTP6 test problem. Same structure as :func:`ctp2` but with constraint parameters (\\theta = 0.1\\pi), (a = 40), (b = 0.5), (c = 1), (d = 2), (e = -2). Here the infeasibility spans the entire search space as a series of infeasible bands; an algorithm must cross several of them to reach the feasible island holding the Pareto-optimal front. Source code in `desdeo/problem/testproblems/ctp_problems.py` ``` def ctp6(n_variables: int) -> Problem: r"""Defines the CTP6 test problem. Same structure as :func:`ctp2` but with constraint parameters $\theta = 0.1\pi$, $a = 40$, $b = 0.5$, $c = 1$, $d = 2$, $e = -2$. Here the infeasibility spans the entire search space as a series of infeasible bands; an algorithm must cross several of them to reach the feasible island holding the Pareto-optimal front. """ return _ctp_problem( name="ctp6", description="The CTP6 test problem.", n_variables=n_variables, constraint_params=[(0.1 * math.pi, 40.0, 0.5, 1.0, 2.0, -2.0)], ) ``` ### ctp7 ``` ctp7(n_variables: int) -> Problem ``` Defines the CTP7 test problem. Same structure as :func:`ctp2` but with constraint parameters (\\theta = -0.05\\pi), (a = 40), (b = 5), (c = 1), (d = 6), (e = 0). The infeasible bands run along the Pareto-optimal region, splitting the unconstrained front into a disconnected set of continuous regions. Source code in `desdeo/problem/testproblems/ctp_problems.py` ``` def ctp7(n_variables: int) -> Problem: r"""Defines the CTP7 test problem. Same structure as :func:`ctp2` but with constraint parameters $\theta = -0.05\pi$, $a = 40$, $b = 5$, $c = 1$, $d = 6$, $e = 0$. The infeasible bands run along the Pareto-optimal region, splitting the unconstrained front into a disconnected set of continuous regions. """ return _ctp_problem( name="ctp7", description="The CTP7 test problem.", n_variables=n_variables, constraint_params=[(-0.05 * math.pi, 40.0, 5.0, 1.0, 6.0, 0.0)], ) ``` ### ctp8 ``` ctp8(n_variables: int) -> Problem ``` Defines the CTP8 test problem. Same structure as :func:`ctp2` but with two simultaneous constraints, combining the entire-search-space difficulties of :func:`ctp6` and :func:`ctp7`: - constraint 1: (\\theta = 0.1\\pi), (a = 40), (b = 0.5), (c = 1), (d = 2), (e = -2); - constraint 2: (\\theta = -0.05\\pi), (a = 40), (b = 2), (c = 1), (d = 6), (e = 0). A solution must satisfy both constraints, leaving the feasible Pareto-optimal region as a small number of disconnected patches. Note: the original chapter only sketches CTP8 as a "combination of two or more" constraints without listing parameters; the values above are the standard ones from Deb (2001). Source code in `desdeo/problem/testproblems/ctp_problems.py` ``` def ctp8(n_variables: int) -> Problem: r"""Defines the CTP8 test problem. Same structure as :func:`ctp2` but with two simultaneous constraints, combining the entire-search-space difficulties of :func:`ctp6` and :func:`ctp7`: - constraint 1: $\theta = 0.1\pi$, $a = 40$, $b = 0.5$, $c = 1$, $d = 2$, $e = -2$; - constraint 2: $\theta = -0.05\pi$, $a = 40$, $b = 2$, $c = 1$, $d = 6$, $e = 0$. A solution must satisfy both constraints, leaving the feasible Pareto-optimal region as a small number of disconnected patches. Note: the original chapter only sketches CTP8 as a "combination of two or more" constraints without listing parameters; the values above are the standard ones from Deb (2001). """ return _ctp_problem( name="ctp8", description="The CTP8 test problem.", n_variables=n_variables, constraint_params=[ (0.1 * math.pi, 40.0, 0.5, 1.0, 2.0, -2.0), (-0.05 * math.pi, 40.0, 2.0, 1.0, 6.0, 0.0), ], ) ``` ### dmitry_forest_problem_disc ``` dmitry_forest_problem_disc() -> Problem ``` Implements the dmitry forest problem using Pareto front representation. Returns: | Name | Type | Description | | --------- | --------- | --------------------------------------------------- | | `Problem` | `Problem` | A problem instance representing the forest problem. | Source code in `desdeo/problem/testproblems/dmitry_forest_problem_discrete.py` ``` def dmitry_forest_problem_disc() -> Problem: """Implements the dmitry forest problem using Pareto front representation. Returns: Problem: A problem instance representing the forest problem. """ # __file__ is desdeo/problem/testproblems/dmitry_forest_problem_discrete.py # CSV is at /tests/data/dmitry_discrete_repr/... path = ( Path(__file__).resolve().parent.parent.parent.parent / "tests/data/dmitry_discrete_repr/dmitry_forest_problem_non_dom_solns.csv" ) obj_names = ["Rev", "HA", "Carb", "DW"] full_names = ["Harvest Revenue", "Habitat Availability", "Carbon Storage", "Deadwood Volume"] units = ["million €", "(unitless)", "thousand Mg C", "thousand m³"] var_name = "index" data = pl.read_csv( path, has_header=True, columns=["Rev", "HA", "Carb", "DW"], separator=",", # decimal_comma=True ) # Remove duplicate rows to ensure unique objective values for each index # The obj values are in 100s, 1000s or 10000s, so just removing the floating point part doesn't change the # objective values significantly (they'd look very similar in visualization anyway). # After that, we can simply remove duplicates and cast back to float for DESDEO calculations. data = data.cast(pl.Int32).unique().cast(pl.Float64) variables = [ Variable( name=var_name, symbol=var_name, variable_type=VariableTypeEnum.integer, lowerbound=0, upperbound=len(data) - 1, initial_value=0, ) ] objectives = [ Objective( name=full_name, symbol=obj_name, unit=unit, objective_type=ObjectiveTypeEnum.data_based, ideal=data[obj_name].max(), nadir=data[obj_name].min(), maximize=True, ) for obj_name, full_name, unit in zip(obj_names, full_names, units, strict=True) ] discrete_def = DiscreteRepresentation( variable_values={"index": list(range(len(data)))}, objective_values=data[[obj.symbol for obj in objectives]].to_dict(), ) return Problem( name="Dmitry Forest Problem (Discrete)", description=( "Defines a forest problem with four objectives: revenue, habitat availability, " "carbon storage, and deadwood." ), variables=variables, objectives=objectives, discrete_representation=discrete_def, is_twice_differentiable=False, ) ``` ### dtlz1 ``` dtlz1(n_variables: int, n_objectives: int) -> Problem ``` Defines the DTLZ1 test problem. The objective functions for DTLZ1 are defined as follows: \[\\begin{align\*} &\\min\_{\\mathbf{x}} \\quad & f_1(\\mathbf{x}) &= \\frac{1}{2}(1+g(\\mathbf{x}_M)) \\prod_{j=1}^{M-1} x_j \\ &\\min\_{\\mathbf{x}} \\quad & f_m(\\mathbf{x}) &= \\frac{1}{2}(1+g(\\mathbf{x}_M)) \\prod_{j=1}^{M-m} x_j (1 - x\_{M-m+1}), \\quad m=2,\\dots,M-1 \\ &\\min\_{\\mathbf{x}} \\quad & f_M(\\mathbf{x}) &= \\frac{1}{2}(1+g(\\mathbf{x}\_M))(1 - x_1) \\end{align\*}\] where \[\\begin{equation} g(\\mathbf{x}_M) = 100\\left\[k + \\sum_{x_i \\in \\mathbf{x}\_M} (x_i - 0.5)^2 - \\cos(20\\pi(x_i-0.5))\\right\], \\end{equation}\] and (\\mathbf{x}_M) represents the last ((n - M + 1)) dimensions of the decision vector. Pareto optimal solutions to the DTLZ1 problem consist of (x_i = 0.5) for all (x_i \\in\\mathbf{x}_{M}), and (\\sum\_{i=1}^{M} f_i = 0.5). Parameters: | Name | Type | Description | Default | | -------------- | ----- | ------------------------------ | ---------- | | `n_variables` | `int` | number of variables. | *required* | | `n_objectives` | `int` | number of objective functions. | *required* | Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------------------------------------------------------- | | `Problem` | `Problem` | an instance of the DTLZ1 problem with n_variables variables and n_objectives objective functions. | References Deb, K., Thiele, L., Laumanns, M., Zitzler, E. (2005). Scalable Test Problems for Evolutionary Multiobjective Optimization. In: Abraham, A., Jain, L., Goldberg, R. (eds) Evolutionary Multiobjective Optimization. Advanced Information and Knowledge Processing. Springer. Source code in `desdeo/problem/testproblems/dtlz_problems.py` ``` def dtlz1(n_variables: int, n_objectives: int) -> Problem: r"""Defines the DTLZ1 test problem. The objective functions for DTLZ1 are defined as follows: \begin{align*} &\min_{\mathbf{x}} \quad & f_1(\mathbf{x}) &= \frac{1}{2}(1+g(\mathbf{x}_M)) \prod_{j=1}^{M-1} x_j \\ &\min_{\mathbf{x}} \quad & f_m(\mathbf{x}) &= \frac{1}{2}(1+g(\mathbf{x}_M)) \prod_{j=1}^{M-m} x_j (1 - x_{M-m+1}), \quad m=2,\dots,M-1 \\ &\min_{\mathbf{x}} \quad & f_M(\mathbf{x}) &= \frac{1}{2}(1+g(\mathbf{x}_M))(1 - x_1) \end{align*} where \begin{equation} g(\mathbf{x}_M) = 100\left[k + \sum_{x_i \in \mathbf{x}_M} (x_i - 0.5)^2 - \cos(20\pi(x_i-0.5))\right], \end{equation} and $\mathbf{x}_M$ represents the last $(n - M + 1)$ dimensions of the decision vector. Pareto optimal solutions to the DTLZ1 problem consist of $x_i = 0.5$ for all $x_i \in\mathbf{x}_{M}$, and $\sum_{i=1}^{M} f_i = 0.5$. Args: n_variables (int): number of variables. n_objectives (int): number of objective functions. Returns: Problem: an instance of the DTLZ1 problem with `n_variables` variables and `n_objectives` objective functions. References: Deb, K., Thiele, L., Laumanns, M., Zitzler, E. (2005). Scalable Test Problems for Evolutionary Multiobjective Optimization. In: Abraham, A., Jain, L., Goldberg, R. (eds) Evolutionary Multiobjective Optimization. Advanced Information and Knowledge Processing. Springer. """ if n_objectives <= 1: raise ValueError("DTLZ1 requires at least 2 objectives.") # function g g_symbol = "g" g_sum = " + ".join( [f"((x_{i} - 0.5)**2 - Cos(20*{np.pi}*(x_{i} - 0.5)))" for i in range(n_objectives, n_variables + 1)] ) k = n_variables - n_objectives + 1 g_expr = f"(100 * ({k} + {g_sum}))" objectives = [] for m in range(1, n_objectives + 1): # function f_m terms = [f"x_{i}" for i in range(1, n_objectives - m + 1)] if m > 1: terms.append(f"(1 - x_{n_objectives - m + 1})") prod_expr = " * ".join(terms) f_m_expr = f"0.5 * (1 + {g_symbol}) * ({prod_expr})" objectives.append( Objective( name=f"f_{m}", symbol=f"f_{m}", func=f_m_expr, maximize=False, ideal=0, nadir=1, # Assuming the range of g and the trigonometric functions is_convex=False, is_linear=False, is_twice_differentiable=True, ) ) variables = [ Variable( name=f"x_{i}", symbol=f"x_{i}", variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=1, initial_value=1.0, ) for i in range(1, n_variables + 1) ] extras = [ ExtraFunction( name="g", symbol=g_symbol, func=g_expr, is_convex=False, is_linear=False, is_twice_differentiable=True ), ] return Problem( name="dtlz1", description="The DTLZ1 test problem.", variables=variables, objectives=objectives, extra_funcs=extras, ) ``` ### dtlz2 ``` dtlz2(n_variables: int, n_objectives: int) -> Problem ``` Defines the DTLZ2 test problem. The objective functions for DTLZ2 are defined as follows, for (i = 1) to (M): \[\\begin{equation} \\underset{\\mathbf{x}}{\\operatorname{min}} f_i(\\mathbf{x}) = (1+g(\\mathbf{x}_M)) \\prod_{j=1}^{M-i} \\cos\\left(x_j \\frac{\\pi}{2}\\right) \\times \\begin{cases} 1 & \\text{if } i=1 \\ \\sin\\left(x\_{(M-i+1)}\\frac{\\pi}{2}\\right) & \\text{otherwise}, \\end{cases} \\end{equation}\] where \[\\begin{equation} g(\\mathbf{x}_M) = \\sum_{x_i \\in \\mathbf{x}\_M} \\left( x_i - 0.5 \\right)^2, \\end{equation}\] and (\\mathbf{x}_M) represents the last (n-k) dimensions of the decision vector. Pareto optimal solutions to the DTLZ2 problem consist of (x_i = 0.5) for all (x_i \\in\\mathbf{x}_{M}), and (\\sum{i=1}^{M} f_i^2 = 1). Parameters: | Name | Type | Description | Default | | -------------- | ----- | ------------------------------ | ---------- | | `n_variables` | `int` | number of variables. | *required* | | `n_objectives` | `int` | number of objective functions. | *required* | Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------------------------------------------------------- | | `Problem` | `Problem` | an instance of the DTLZ2 problem with n_variables variables and n_objectives objective functions. | References Deb, K., Thiele, L., Laumanns, M., Zitzler, E. (2005). Scalable Test Problems for Evolutionary Multiobjective Optimization. In: Abraham, A., Jain, L., Goldberg, R. (eds) Evolutionary Multiobjective Optimization. Advanced Information and Knowledge Processing. Springer. Source code in `desdeo/problem/testproblems/dtlz_problems.py` ``` def dtlz2(n_variables: int, n_objectives: int) -> Problem: r"""Defines the DTLZ2 test problem. The objective functions for DTLZ2 are defined as follows, for $i = 1$ to $M$: \begin{equation} \underset{\mathbf{x}}{\operatorname{min}} f_i(\mathbf{x}) = (1+g(\mathbf{x}_M)) \prod_{j=1}^{M-i} \cos\left(x_j \frac{\pi}{2}\right) \times \begin{cases} 1 & \text{if } i=1 \\ \sin\left(x_{(M-i+1)}\frac{\pi}{2}\right) & \text{otherwise}, \end{cases} \end{equation} where \begin{equation} g(\mathbf{x}_M) = \sum_{x_i \in \mathbf{x}_M} \left( x_i - 0.5 \right)^2, \end{equation} and $\mathbf{x}_M$ represents the last $n-k$ dimensions of the decision vector. Pareto optimal solutions to the DTLZ2 problem consist of $x_i = 0.5$ for all $x_i \in\mathbf{x}_{M}$, and $\sum{i=1}^{M} f_i^2 = 1$. Args: n_variables (int): number of variables. n_objectives (int): number of objective functions. Returns: Problem: an instance of the DTLZ2 problem with `n_variables` variables and `n_objectives` objective functions. References: Deb, K., Thiele, L., Laumanns, M., Zitzler, E. (2005). Scalable Test Problems for Evolutionary Multiobjective Optimization. In: Abraham, A., Jain, L., Goldberg, R. (eds) Evolutionary Multiobjective Optimization. Advanced Information and Knowledge Processing. Springer. """ # function g g_symbol = "g" g_expr = " + ".join([f"(x_{i} - 0.5)**2" for i in range(n_objectives, n_variables + 1)]) objectives = [] for m in range(1, n_objectives + 1): # function f_m prod_expr = " * ".join([f"Cos(0.5 * {np.pi} * x_{i})" for i in range(1, n_objectives - m + 1)]) if m > 1: prod_expr += f"{' * ' if prod_expr != '' else ''}Sin(0.5 * {np.pi} * x_{n_objectives - m + 1})" if prod_expr == "": prod_expr = "1" # When m == n_objectives, the product is empty, implying f_M = g. f_m_expr = f"(1 + {g_symbol}) * ({prod_expr})" objectives.append( Objective( name=f"f_{m}", symbol=f"f_{m}", func=f_m_expr, maximize=False, ideal=0, nadir=1, # Assuming the range of g and the trigonometric functions is_convex=False, is_linear=False, is_twice_differentiable=True, ) ) variables = [ Variable( name=f"x_{i}", symbol=f"x_{i}", variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=1, initial_value=1.0, ) for i in range(1, n_variables + 1) ] extras = [ ExtraFunction( name="g", symbol=g_symbol, func=g_expr, is_convex=False, is_linear=False, is_twice_differentiable=True ), ] return Problem( name="dtlz2", description="The DTLZ2 test problem.", variables=variables, objectives=objectives, extra_funcs=extras, ) ``` ### dtlz4 ``` dtlz4( n_variables: int, n_objectives: int, alpha: float = 100.0, ) -> Problem ``` Defines the DTLZ4 test problem. The objective functions for DTLZ4 are defined as follows, for (i = 1) to (M): \[\\begin{equation} \\underset{\\mathbf{x}}{\\operatorname{min}} f_i(\\mathbf{x}) = (1+g(\\mathbf{x}_M)) \\prod_{j=1}^{M-i} \\cos\\left(x_j^{\\alpha} \\frac{\\pi}{2}\\right) \\times \\begin{cases} 1 & \\text{if } i=1 \\ \\sin\\left(x\_{(M-i+1)}^{\\alpha}\\frac{\\pi}{2}\\right) & \\text{otherwise}, \\end{cases} \\end{equation}\] where \[\\begin{equation} g(\\mathbf{x}_M) = \\sum_{x_i \\in \\mathbf{x}\_M} \\left( x_i - 0.5 \\right)^2, \\end{equation}\] and (\\mathbf{x}_M) represents the last (n-k) dimensions of the decision vector. Pareto optimal solutions to the DTLZ4 problem consist of (x_i = 0.5) for all (x_i \\in\\mathbf{x}_{M}), and (\\sum{i=1}^{M} f_i^2 = 1). Parameters: | Name | Type | Description | Default | | -------------- | ------- | ----------------------------- | ---------- | | `n_variables` | `int` | number of variables | *required* | | `n_objectives` | `int` | number of objective functions | *required* | | `alpha` | `float` | exponent | `100.0` | Returns: | Name | Type | Description | | --------- | --------- | ----------------------------------------------------------------------------------------------- | | `Problem` | `Problem` | an instance of a DTLZ4 problem with n_variables variables and n_objectives objective functions. | References Deb, K., Thiele, L., Laumanns, M., Zitzler, E. (2005). Scalable Test Problems for Evolutionary Multiobjective Optimization. In: Abraham, A., Jain, L., Goldberg, R. (eds) Evolutionary Multiobjective Optimization. Advanced Information and Knowledge Processing. Springer. Source code in `desdeo/problem/testproblems/dtlz_problems.py` ``` def dtlz4(n_variables: int, n_objectives: int, alpha: float = 100.0) -> Problem: r"""Defines the DTLZ4 test problem. The objective functions for DTLZ4 are defined as follows, for $i = 1$ to $M$: \begin{equation} \underset{\mathbf{x}}{\operatorname{min}} f_i(\mathbf{x}) = (1+g(\mathbf{x}_M)) \prod_{j=1}^{M-i} \cos\left(x_j^{\alpha} \frac{\pi}{2}\right) \times \begin{cases} 1 & \text{if } i=1 \\ \sin\left(x_{(M-i+1)}^{\alpha}\frac{\pi}{2}\right) & \text{otherwise}, \end{cases} \end{equation} where \begin{equation} g(\mathbf{x}_M) = \sum_{x_i \in \mathbf{x}_M} \left( x_i - 0.5 \right)^2, \end{equation} and $\mathbf{x}_M$ represents the last $n-k$ dimensions of the decision vector. Pareto optimal solutions to the DTLZ4 problem consist of $x_i = 0.5$ for all $x_i \in\mathbf{x}_{M}$, and $\sum{i=1}^{M} f_i^2 = 1$. Args: n_variables: number of variables n_objectives: number of objective functions alpha: exponent Returns: Problem: an instance of a DTLZ4 problem with `n_variables` variables and `n_objectives` objective functions. References: Deb, K., Thiele, L., Laumanns, M., Zitzler, E. (2005). Scalable Test Problems for Evolutionary Multiobjective Optimization. In: Abraham, A., Jain, L., Goldberg, R. (eds) Evolutionary Multiobjective Optimization. Advanced Information and Knowledge Processing. Springer. """ # function g g_symbol = "g" g_expr = " + ".join([f"(x_{i} - 0.5)**2" for i in range(n_objectives, n_variables + 1)]) objectives = [] for m in range(1, n_objectives + 1): # function f_m prod_expr = " * ".join([f"Cos(0.5 * {np.pi} * x_{i}**{alpha})" for i in range(1, n_objectives - m + 1)]) if m > 1: prod_expr += f"{' * ' if prod_expr != '' else ''}Sin(0.5 * {np.pi} * x_{n_objectives - m + 1}**{alpha})" if prod_expr == "": prod_expr = "1" # Only reached when n_objectives == 1: no trig terms, so f_1 = 1 + g f_m_expr = f"(1 + {g_symbol}) * ({prod_expr})" objectives.append( Objective( name=f"f_{m}", symbol=f"f_{m}", func=f_m_expr, maximize=False, ideal=0, nadir=1, # Assuming the range of g and the trigonometric functions is_convex=False, is_linear=False, is_twice_differentiable=True, ) ) variables = [ Variable( name=f"x_{i}", symbol=f"x_{i}", variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=1, initial_value=1.0, ) for i in range(1, n_variables + 1) ] extras = [ ExtraFunction( name="g", symbol=g_symbol, func=g_expr, is_convex=False, is_linear=False, is_twice_differentiable=True ), ] return Problem( name="dtlz4", description="The DTLZ4 test problem.", variables=variables, objectives=objectives, extra_funcs=extras, ) ``` ### forest_problem_discrete ``` forest_problem_discrete() -> Problem ``` Implements the forest problem using Pareto front representation. Returns: | Name | Type | Description | | --------- | --------- | --------------------------------------------------- | | `Problem` | `Problem` | A problem instance representing the forest problem. | Source code in `desdeo/problem/testproblems/forest_problem.py` ``` def forest_problem_discrete() -> Problem: """Implements the forest problem using Pareto front representation. Returns: Problem: A problem instance representing the forest problem. """ filename = "datasets/forest_holding_4.csv" path = Path(__file__).parent.parent.parent.parent / filename obj_names = ["stock", "harvest_value", "npv"] var_name = "index" data = pl.read_csv( path, has_header=True, columns=["stock", "harvest_value", "npv"], separator=";", decimal_comma=True ) variables = [ Variable( name=var_name, symbol=var_name, variable_type=VariableTypeEnum.integer, lowerbound=0, upperbound=len(data) - 1, initial_value=0, ) ] objectives = [ Objective( name=obj_name, symbol=obj_name, objective_type=ObjectiveTypeEnum.data_based, ideal=data[obj_name].max(), nadir=data[obj_name].min(), maximize=True, ) for obj_name in obj_names ] discrete_def = DiscreteRepresentation( variable_values={"index": list(range(len(data)))}, objective_values=data[[obj.symbol for obj in objectives]].to_dict(), ) return Problem( name="Finnish Forest Problem (Discrete)", description="Defines a forest problem with three objectives: stock, harvest value, and net present value.", variables=variables, objectives=objectives, discrete_representation=discrete_def, ) ``` ### forest_problem_income_carbon_habitat ``` forest_problem_income_carbon_habitat( *, non_dominated_only: bool = False ) -> Problem ``` Defines a discrete Finnish forest management problem with ecological objectives. A forest is divided into managerial areas known as stands. A management plan, such as clearing, thinning, or leaving a stand untouched, is chosen for each stand, and the consequences are aggregated over the whole forest. Three consequences are considered, and all of them are to be maximized: - the income from sold timber, - the carbon dioxide stored in the trees, - the combined habitat suitability index, describing how habitable the forest is for fauna. The objectives conflict. Felling trees and selling the timber raises income while releasing stored carbon and leaving the stand uninhabitable, and leaving a stand untouched maximizes stored carbon while yielding no income. The problem is given purely as a precomputed set of objective vectors, simulated with SIMO over a one hundred year horizon. The management plan behind each solution was not published, so the decision variables cannot be recovered and the only variable here is an index into the set. The ideal and nadir points are taken from the set rather than from a payoff table. Note The published set is not filtered for dominance: of its 1728 rows, 1247 are non-dominated. Pass `non_dominated_only=True` to keep only those. Dropping rows leaves the ideal point untouched and can only tighten the nadir point. For this data the stored carbon dioxide and the habitat index both move, while the worst income belongs to a non-dominated row and so stays put. The default reproduces the set as published. Note The source publications scale the objectives for display, by 1e-7 for the income, 1e-9 for the stored carbon dioxide, and 1e-4 for the habitat index. The values here are unscaled. Parameters: | Name | Type | Description | Default | | -------------------- | ------ | --------------------------------------------------------------------------- | ------- | | `non_dominated_only` | `bool` | whether to drop the dominated rows of the published set. Defaults to False. | `False` | Returns: | Name | Type | Description | | --------- | --------- | --------------------------------------- | | `Problem` | `Problem` | the discrete forest management problem. | References Misitano, G. (2020). INFRINGER: a novel interactive multi-objective optimization method able to learn a decision maker's preferences utilizing machine learning. Master's thesis, University of Jyvaskyla. http://urn.fi/URN:NBN:fi:jyu-202007065235 Misitano, G. (2020). Interactively learning the preferences of a decision maker in multi-objective optimization utilizing belief-rules. In 2020 IEEE Symposium Series on Computational Intelligence (SSCI), 133-140. https://doi.org/10.1109/SSCI47803.2020.9308316 Misitano, G., Afsar, B., Larraga, G., & Miettinen, K. (2022). Towards explainable interactive multiobjective optimization: R-XIMO. Autonomous Agents and Multi-Agent Systems, 36(2), 43. https://doi.org/10.1007/s10458-022-09577-3 Source code in `desdeo/problem/testproblems/forest_problem.py` ``` def forest_problem_income_carbon_habitat(*, non_dominated_only: bool = False) -> Problem: r"""Defines a discrete Finnish forest management problem with ecological objectives. A forest is divided into managerial areas known as stands. A management plan, such as clearing, thinning, or leaving a stand untouched, is chosen for each stand, and the consequences are aggregated over the whole forest. Three consequences are considered, and all of them are to be maximized: - the income from sold timber, - the carbon dioxide stored in the trees, - the combined habitat suitability index, describing how habitable the forest is for fauna. The objectives conflict. Felling trees and selling the timber raises income while releasing stored carbon and leaving the stand uninhabitable, and leaving a stand untouched maximizes stored carbon while yielding no income. The problem is given purely as a precomputed set of objective vectors, simulated with SIMO over a one hundred year horizon. The management plan behind each solution was not published, so the decision variables cannot be recovered and the only variable here is an index into the set. The ideal and nadir points are taken from the set rather than from a payoff table. Note: The published set is not filtered for dominance: of its 1728 rows, 1247 are non-dominated. Pass `non_dominated_only=True` to keep only those. Dropping rows leaves the ideal point untouched and can only tighten the nadir point. For this data the stored carbon dioxide and the habitat index both move, while the worst income belongs to a non-dominated row and so stays put. The default reproduces the set as published. Note: The source publications scale the objectives for display, by 1e-7 for the income, 1e-9 for the stored carbon dioxide, and 1e-4 for the habitat index. The values here are unscaled. Args: non_dominated_only (bool, optional): whether to drop the dominated rows of the published set. Defaults to False. Returns: Problem: the discrete forest management problem. References: Misitano, G. (2020). INFRINGER: a novel interactive multi-objective optimization method able to learn a decision maker's preferences utilizing machine learning. Master's thesis, University of Jyvaskyla. http://urn.fi/URN:NBN:fi:jyu-202007065235 Misitano, G. (2020). Interactively learning the preferences of a decision maker in multi-objective optimization utilizing belief-rules. In 2020 IEEE Symposium Series on Computational Intelligence (SSCI), 133-140. https://doi.org/10.1109/SSCI47803.2020.9308316 Misitano, G., Afsar, B., Larraga, G., & Miettinen, K. (2022). Towards explainable interactive multiobjective optimization: R-XIMO. Autonomous Agents and Multi-Agent Systems, 36(2), 43. https://doi.org/10.1007/s10458-022-09577-3 """ path = Path(__file__).parent.parent.parent.parent / "datasets/forest_income_carbon_habitat.csv" # The published file carries a constant 'dummy' column, which an earlier # version of DESDEO required to stand in for the missing decision variables. columns = {"Income": "income", "Carbon": "stored_co2", "Habitat index": "habitat_index"} names = { "income": "Income", "stored_co2": "Stored CO2", "habitat_index": "Combined habitat suitability index", } data = pl.read_csv(path, has_header=True, columns=list(columns)).rename(columns) if non_dominated_only: mask = _non_dominated_mask(data.to_numpy()) data = data.filter(mask) variables = [ Variable( name="index", symbol="index", variable_type=VariableTypeEnum.integer, lowerbound=0, upperbound=len(data) - 1, initial_value=0, ) ] objectives = [ Objective( name=names[symbol], symbol=symbol, objective_type=ObjectiveTypeEnum.data_based, ideal=data[symbol].max(), nadir=data[symbol].min(), maximize=True, ) for symbol in columns.values() ] discrete_def = DiscreteRepresentation( variable_values={"index": list(range(len(data)))}, objective_values=data.to_dict(as_series=False), non_dominated=non_dominated_only, ) return Problem( name="Finnish forest problem with ecological objectives (discrete)", description=( "Defines a discrete Finnish forest management problem with three objectives to be maximized: " "income from sold timber, stored carbon dioxide, and the combined habitat suitability index." ), variables=variables, objectives=objectives, discrete_representation=discrete_def, ) ``` ### gaa ``` gaa(*, fold_constraint: bool = False) -> Problem ``` Defines the General Aviation Aircraft product family design problem. Three aircraft -- a 2-, 4- and 6-seat variant -- are designed as one family. Each has nine design variables, giving 27 in total, and nine performance responses predicted by second-order polynomial response surfaces in those variables. Writing (R\_{r,s}) for response (r) of the (s)-seat aircraft, and (z\_{i,s}) for its (i)-th design variable scaled to ([-1, 1]): [\\begin{align} &\\min\_{\\mathbf{x}} & f_1 \\ldots f_6 & = \\max\_{s \\in {2,4,6}} R\_{r,s}, & r & \\in {\\text{noise}, \\text{wemp}, \\text{doc}, \\text{rough}, \\text{wfuel}, \\text{purch}} \\ &\\max\_{\\mathbf{x}} & f_7 \\ldots f_9 & = \\min\_{s \\in {2,4,6}} R\_{r,s}, & r & \\in {\\text{range}, \\text{ldmax}, \\text{vcmax}} \\ &\\min\_{\\mathbf{x}} & f\_{10} & = \\sqrt{\\sum\_{i=1}^{9}\\sum\_{s \\in {2,4,6}} \\left(z\_{i,s} - \\bar{z_i}\\right)^2} \\end{align}] The tenth objective is the *product family penalty function*: the spread of the three aircraft around their common mean design. Driving it to zero makes the three variants identical, which is the cheapest family to build and the worst-performing one, so it trades against all nine performance objectives at once. That trade is what the problem exists to study. The constraint is the total violation of eighteen performance limits -- six responses on each of the three aircraft, each normalised by its limit and clamped at zero: \[\\begin{align} g(\\mathbf{x}) = \\sum\_{s \\in {2,4,6}} \\left( \\sum\_{r} \\max\\left{\\frac{R\_{r,s} - L\_{r,s}}{L\_{r,s}}, 0\\right} - \\max\\left{\\frac{L\_{\\text{range},s} - R\_{\\text{range},s}}{L\_{\\text{range},s}}, 0\\right} \\right) \\leq 0 \\end{align}\] Every term is clamped at zero, so (g \\geq 0) always and a solution is feasible exactly when it meets all eighteen limits. Note The three variants have **different** response surface coefficients -- 27 fitted surfaces in all, not 9 reused three times. The running maxima of the first six objectives start at 0 and the running minima of the next three start at 200 000, exactly as in the reference implementation. Those bounds never bind on the design box, but they are kept so that the two implementations agree bit for bit. The reference implementation also computes a set of `*_DEV` goal deviations that nothing then reads. They are dead code there and are not reproduced here. Parameters: | Name | Type | Description | Default | | ----------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `fold_constraint` | `bool` | if True, return the constraint violation as an eleventh objective and no constraints, in the manner of the RE suite, which makes the problem bound-constrained. If False, return the ten objectives and the constraint as published. Defaults to False. | `False` | Returns: | Name | Type | Description | | --------- | --------- | --------------------------------------------------------------------------- | | `Problem` | `Problem` | an instance of the General Aviation Aircraft product family design problem. | Source code in `desdeo/problem/testproblems/gaa_problem.py` ``` def gaa(*, fold_constraint: bool = False) -> Problem: r"""Defines the General Aviation Aircraft product family design problem. Three aircraft -- a 2-, 4- and 6-seat variant -- are designed as one family. Each has nine design variables, giving 27 in total, and nine performance responses predicted by second-order polynomial response surfaces in those variables. Writing $R_{r,s}$ for response $r$ of the $s$-seat aircraft, and $z_{i,s}$ for its $i$-th design variable scaled to $[-1, 1]$: \begin{align} &\min_{\mathbf{x}} & f_1 \ldots f_6 & = \max_{s \in \{2,4,6\}} R_{r,s}, & r & \in \{\text{noise}, \text{wemp}, \text{doc}, \text{rough}, \text{wfuel}, \text{purch}\} \\ &\max_{\mathbf{x}} & f_7 \ldots f_9 & = \min_{s \in \{2,4,6\}} R_{r,s}, & r & \in \{\text{range}, \text{ldmax}, \text{vcmax}\} \\ &\min_{\mathbf{x}} & f_{10} & = \sqrt{\sum_{i=1}^{9}\sum_{s \in \{2,4,6\}} \left(z_{i,s} - \bar{z_i}\right)^2} \end{align} The tenth objective is the *product family penalty function*: the spread of the three aircraft around their common mean design. Driving it to zero makes the three variants identical, which is the cheapest family to build and the worst-performing one, so it trades against all nine performance objectives at once. That trade is what the problem exists to study. The constraint is the total violation of eighteen performance limits -- six responses on each of the three aircraft, each normalised by its limit and clamped at zero: \begin{align} g(\mathbf{x}) = \sum_{s \in \{2,4,6\}} \left( \sum_{r} \max\left\{\frac{R_{r,s} - L_{r,s}}{L_{r,s}}, 0\right\} + \max\left\{\frac{L_{\text{range},s} - R_{\text{range},s}}{L_{\text{range},s}}, 0\right\} \right) \leq 0 \end{align} Every term is clamped at zero, so $g \geq 0$ always and a solution is feasible exactly when it meets all eighteen limits. Note: The three variants have **different** response surface coefficients -- 27 fitted surfaces in all, not 9 reused three times. The running maxima of the first six objectives start at 0 and the running minima of the next three start at 200 000, exactly as in the reference implementation. Those bounds never bind on the design box, but they are kept so that the two implementations agree bit for bit. The reference implementation also computes a set of `*_DEV` goal deviations that nothing then reads. They are dead code there and are not reproduced here. Args: fold_constraint (bool, optional): if `True`, return the constraint violation as an eleventh objective and no constraints, in the manner of the RE suite, which makes the problem bound-constrained. If `False`, return the ten objectives and the constraint as published. Defaults to `False`. Returns: Problem: an instance of the General Aviation Aircraft product family design problem. """ variables = [] extras = [] for aircraft, seats in enumerate(_SEATS): for i, (design, description, centre, half_range) in enumerate(_DESIGN): symbol = f"x_{aircraft * len(_DESIGN) + i + 1}" variables.append( Variable( name=f"{description} ({seats}-seat)", symbol=symbol, variable_type=VariableTypeEnum.real, lowerbound=centre - half_range, upperbound=centre + half_range, initial_value=centre, ) ) extras.append( ExtraFunction( name=f"scaled {design} ({seats}-seat)", symbol=_scaled_symbol(design, seats), func=f"({symbol} - {centre!r}) / {half_range!r}", is_linear=True, is_convex=True, is_twice_differentiable=True, ) ) for response, description, _ in _RESPONSES: for seats in _SEATS: extras.append( ExtraFunction( name=f"{description} ({seats}-seat)", symbol=f"{response}_{seats}", func=_surface_expression(response, seats), is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) ) objectives = [] for index, (response, description, maximize) in enumerate(_RESPONSES, start=1): across = ", ".join(f"{response}_{seats}" for seats in _SEATS) # The starting value of the reference implementation's running extremum comes first. aggregate = f"Min(200000, {across})" if maximize else f"Max(0, {across})" objectives.append( Objective( # Both aggregations take the worst case: the largest of the six that are minimised, # the smallest of the three that are maximised. name=f"worst {description} across the family", symbol=f"f_{index}", func=aggregate, objective_type=ObjectiveTypeEnum.analytical, maximize=maximize, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) ) for design, description, _, _ in _DESIGN: across = " + ".join(_scaled_symbol(design, seats) for seats in _SEATS) extras.append( ExtraFunction( name=f"family mean of the scaled {description}", symbol=f"{design}_mean", func=f"({across}) / {len(_SEATS)}", is_linear=True, is_convex=True, is_twice_differentiable=True, ) ) spread = " + ".join( f"({_scaled_symbol(design, seats)} - {design}_mean)**2" for design, *_ in _DESIGN for seats in _SEATS ) objectives.append( Objective( name="product family penalty function", symbol=f"f_{len(_RESPONSES) + 1}", func=f"Sqrt({spread})", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) ) violations = [] for response, limits in _CONSTRAINT_LIMITS.items(): for seats in _SEATS: limit = limits[seats] symbol = f"{response}_{seats}" # The range must exceed its limit; every other response must stay below it. excess = f"({limit!r} - {symbol})" if response == "range" else f"({symbol} - {limit!r})" violations.append(f"Max({excess} / {limit!r}, 0)") total_violation = " + ".join(violations) if fold_constraint: objectives.append( Objective( name="total performance limit violation", symbol=f"f_{len(_RESPONSES) + 2}", func=total_violation, objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) ) constraints = None else: constraints = [ Constraint( name="total performance limit violation", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func=total_violation, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) ] return Problem( name="gaa", description="The General Aviation Aircraft product family design problem", variables=variables, objectives=objectives, constraints=constraints, extra_funcs=extras, ) ``` ### generate_solar_profile ``` generate_solar_profile() -> np.ndarray ``` Generate hourly solar production per 160 W panel from June 1 to August 31. Uses a clear-sky sine curve based on approximate sunrise/sunset times for 60°N latitude, scaled by a daily cloudiness factor sampled uniformly from [0.2, 1.0] (up to 80% reduction). On a clear summer day the panel produces its nominal 0.16 kWh/h at solar noon. Returns: | Type | Description | | --------- | ------------------------------------------------------------------ | | `ndarray` | A numpy array of shape (2208,) with kWh output per panel per hour. | Source code in `desdeo/problem/testproblems/summer_cabin_electricity.py` ``` def generate_solar_profile() -> np.ndarray: """Generate hourly solar production per 160 W panel from June 1 to August 31. Uses a clear-sky sine curve based on approximate sunrise/sunset times for 60°N latitude, scaled by a daily cloudiness factor sampled uniformly from [0.2, 1.0] (up to 80% reduction). On a clear summer day the panel produces its nominal 0.16 kWh/h at solar noon. Returns: A numpy array of shape (2208,) with kWh output per panel per hour. """ rng = np.random.default_rng(42) time_index = pd.date_range("2025-06-01", "2025-08-31 23:00", freq="h") panel_peak_kw = 0.16 # kW nominal per panel solar_noon = 13.0 # hour of peak irradiance (local time) lat = np.radians(60.0) days = pd.date_range("2025-06-01", "2025-08-31", freq="D") cloudiness = {d.date(): rng.uniform(0.2, 1.0) for d in days} profile = [] for ts in time_index: doy = ts.day_of_year dec = np.radians(23.45 * np.sin(np.radians(360.0 / 365.0 * (doy - 80)))) cos_ha = np.clip(-np.tan(lat) * np.tan(dec), -1.0, 1.0) day_len = 2.0 * np.degrees(np.arccos(cos_ha)) / 15.0 sunrise = solar_noon - day_len / 2.0 sunset = solar_noon + day_len / 2.0 hour = ts.hour if sunrise <= hour <= sunset: clear_sky = panel_peak_kw * np.sin(np.pi * (hour - sunrise) / (sunset - sunrise)) else: clear_sky = 0.0 profile.append(max(0.0, clear_sky * cloudiness[ts.date()])) return np.array(profile) ``` ### generate_summer_cabin_electricity_data ``` generate_summer_cabin_electricity_data() ``` Generates synthetic hourly electricity load and temperature data for a summer cabin from June 1 to August 31. Source code in `desdeo/problem/testproblems/summer_cabin_electricity.py` ``` def generate_summer_cabin_electricity_data(): # noqa: C901 """Generates synthetic hourly electricity load and temperature data for a summer cabin from June 1 to August 31.""" rng = np.random.default_rng(6969) time_index = pd.date_range("2025-06-01", "2025-08-31 23:00", freq="h") # --- Temperature model --- def seasonal_temp(ts): match ts.month: case 6: return 14 case 7: return 18 case _: return 15 def daily_temp(hour): # peak at 15:00, trough at 04:00 return 5 * np.sin((hour - 15) / 24 * 2 * np.pi) def temperature(ts): return seasonal_temp(ts) + daily_temp(ts.hour) + rng.normal(0, 1.5) # --- Heating --- def heating_load(temp): threshold = 18 k = 0.2 return max(0, (threshold - temp) * k) # --- Base load --- def base_load(): return rng.uniform(0.2, 0.35) # --- Daily pattern --- def daily_usage(hour): if hour < 6: return 0.1 if hour < 9: return 0.8 if hour < 17: return 0.4 if hour < 22: return 1.0 return 0.3 # --- Cooking spikes --- def cooking_spike(ts): if ts.hour in [7, 12, 18] and rng.random() < 0.5: return rng.uniform(0.8, 1.8) return 0 # --- Sauna --- def sauna_spike(ts): if ts.weekday() in [4, 5, 6]: # Fri-Sun # noqa: SIM102 if 18 <= ts.hour <= 21 and rng.random() < 0.25: return rng.uniform(5, 8) return 0 loads = [] temps = [] for ts in time_index: temps.append(temperature(ts)) load = 0 load += base_load() load += daily_usage(ts.hour) load += heating_load(temperature(ts)) load += cooking_spike(ts) # load += sauna_spike(ts) # no one uses electric sauna in the summer cabin load += rng.normal(0, 0.05) loads.append(max(load, 0.15)) prices_eur_kwh = np.load(_PRICES_PATH)["prices"] / 1000.0 return pd.DataFrame( {"load_kWh": loads, "temperature_C": temps, "price_EUR_kWh": prices_eur_kwh}, index=time_index, ) ``` ### lame_superspheres ``` lame_superspheres( n_variables: int, n_objectives: int, gamma: float = 2.0 ) -> Problem ``` Defines the Lamé superspheres test problem. The objective functions for the Lamé superspheres problem are defined as follows, for (i = 1) to (M): # \[\\begin{equation} f_i(\\mathbf{x}) (1 + g(\\mathbf{x}\_M)) \\tilde{p}\_i(\\mathbf{x}), \\end{equation}\] where the hypersphere parametrization follows Eq. (10) [\\begin{equation} p_1 = \\cos(\\theta_1), \\end{equation}] [\\begin{equation} p_2 = \\sin(\\theta_1)\\cos(\\theta_2), \\end{equation}] [\\begin{equation} p_3 = \\sin(\\theta_1)\\sin(\\theta_2)\\cos(\\theta_3), \\end{equation}] [\\begin{equation} \\vdots \\end{equation}] [\\begin{equation} p_M = \\prod\_{j=1}^{M-1} \\sin(\\theta_j). \\end{equation}] The Lamé supersphere coordinates are then obtained as [\\begin{equation} \\tilde{p}\_i = p_i^{2/\\gamma}. \\end{equation}] The distance function is # \[\\begin{equation} g(\\mathbf{x}\_M) \\sqrt{ \\sum\_{x_i \\in \\mathbf{x}\_M} x_i^2 }. \\end{equation}\] The parameter (\\gamma) controls the curvature of the Pareto front: - (\\gamma < 1) gives a convex Pareto front. - (\\gamma = 1) gives a linear Pareto front. - (\\gamma = 2) gives a spherical (concave) Pareto front. - (\\gamma > 2) gives a more boxy, strongly concave Pareto front. Parameters: | Name | Type | Description | Default | | -------------- | ------- | ------------------------------------------ | ---------- | | `n_variables` | `int` | Number of variables. | *required* | | `n_objectives` | `int` | Number of objectives. | *required* | | `gamma` | `float` | Lamé exponent controlling front curvature. | `2.0` | Returns: | Name | Type | Description | | --------- | --------- | --------------------------------- | | `Problem` | `Problem` | A Lamé superspheres test problem. | References Emmerich, M. T. M., & Deutz, A. H. (2007). Test Problems Based on Lamé Superspheres. EMO 2007, LNCS 4403, 922-936. Source code in `desdeo/problem/testproblems/lame_superspheres_problem.py` ``` def lame_superspheres( n_variables: int, n_objectives: int, gamma: float = 2.0, ) -> Problem: r"""Defines the Lamé superspheres test problem. The objective functions for the Lamé superspheres problem are defined as follows, for $i = 1$ to $M$: \begin{equation} f_i(\mathbf{x}) = (1 + g(\mathbf{x}_M)) \tilde{p}_i(\mathbf{x}), \end{equation} where the hypersphere parametrization follows Eq. (10) \begin{equation} p_1 = \cos(\theta_1), \end{equation} \begin{equation} p_2 = \sin(\theta_1)\cos(\theta_2), \end{equation} \begin{equation} p_3 = \sin(\theta_1)\sin(\theta_2)\cos(\theta_3), \end{equation} \begin{equation} \vdots \end{equation} \begin{equation} p_M = \prod_{j=1}^{M-1} \sin(\theta_j). \end{equation} The Lamé supersphere coordinates are then obtained as \begin{equation} \tilde{p}_i = p_i^{2/\gamma}. \end{equation} The distance function is \begin{equation} g(\mathbf{x}_M) = \sqrt{ \sum_{x_i \in \mathbf{x}_M} x_i^2 }. \end{equation} The parameter $\gamma$ controls the curvature of the Pareto front: - $\gamma < 1$ gives a convex Pareto front. - $\gamma = 1$ gives a linear Pareto front. - $\gamma = 2$ gives a spherical (concave) Pareto front. - $\gamma > 2$ gives a more boxy, strongly concave Pareto front. Args: n_variables: Number of variables. n_objectives: Number of objectives. gamma: Lamé exponent controlling front curvature. Returns: Problem: A Lamé superspheres test problem. References: Emmerich, M. T. M., & Deutz, A. H. (2007). Test Problems Based on Lamé Superspheres. EMO 2007, LNCS 4403, 922-936. """ if n_objectives < 2: # noqa: PLR2004 raise ValueError(f"n_objectives must be at least 2, got {n_objectives}.") if n_variables < n_objectives: raise ValueError( "n_variables must be greater than or equal to n_objectives " f"(need at least {n_objectives} variables), got {n_variables}." ) g_symbol = "g" sum_expr = " + ".join([f"(x_{i})**2" for i in range(n_objectives, n_variables + 1)]) g_expr = f"Sqrt({sum_expr})" objectives = [] for m in range(1, n_objectives + 1): if m == 1: angular_expr = f"Cos(0.5 * {np.pi} * x_1)" elif m < n_objectives: factors = [f"Sin(0.5 * {np.pi} * x_{i})" for i in range(1, m)] factors.append(f"Cos(0.5 * {np.pi} * x_{m})") angular_expr = " * ".join(factors) else: angular_expr = " * ".join([f"Sin(0.5 * {np.pi} * x_{i})" for i in range(1, n_objectives)]) f_m_expr = f"(1 + {g_symbol}) * (({angular_expr})**({2 / gamma}))" objectives.append( Objective( name=f"f_{m}", symbol=f"f_{m}", func=f_m_expr, maximize=False, ideal=0, nadir=1, is_convex=False, is_linear=False, is_twice_differentiable=True, ) ) variables = [ Variable( name=f"x_{i}", symbol=f"x_{i}", variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=1, initial_value=1.0, ) for i in range(1, n_variables + 1) ] extras = [ ExtraFunction( name="g", symbol=g_symbol, func=g_expr, is_convex=False, is_linear=False, is_twice_differentiable=True, ), ] return Problem( name="lame_superspheres", description="Lamé superspheres test problem.", variables=variables, objectives=objectives, extra_funcs=extras, ) ``` ### mcwb_equilateral_tbeam_problem ``` mcwb_equilateral_tbeam_problem() -> Problem ``` Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem using an equilateral T-beam cross-section. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, ( f_1 = W_c + B_c ), where ( W_c ) is the weld cost and ( B_c ) is the beam cost. 1. Minimize the deflection of the beam, ( f_2 = \\frac{P L^3}{3 E I_x} ), where ( P ) is the applied load, ( L ) is the beam length, ( E ) is the Young's modulus, and ( I_x ) is the moment of inertia. Constraints: 1. Shear stress constraint: ( \\tau \\leq \\tau\_{max} ), where ( \\tau ) is the combined shear stress and ( \\tau\_{max} ) is the maximum shear stress. 1. Normal stress constraint: ( \\sigma_x \\leq \\sigma\_{max} ), where ( \\sigma_x ) is the bending stress and ( \\sigma\_{max} ) is the maximum allowable normal stress. 1. Buckling constraint: ( P \\leq P_c ), where ( P_c ) is the critical buckling load. 1. Weld height constraint: ( x_1 \\leq x_4 ), ensuring that the weld height ( x_1 ) is less than or equal to the flange/web thickness ( x_4 ). 1. Flange thickness constraint: ( x_4 \\geq x_3 ), ensuring that the flange thickness ( x_4 ) is greater than or equal to the beam height ( x_3 ). Where: - ( x_1 ) is the weld height. - ( x_2 ) is the weld length. - ( x_3 ) is the beam height. - ( x_4 ) is the beam thickness (flange/web thickness). The parameters are defined as: - ( P = 30000 , \\text{N} ) (load), - ( L = 0.5 , \\text{m} ) (beam length), - ( E = 200 \\times 10^9 , \\text{Pa} ) (Young's modulus), - ( \\tau\_{max} = 95 \\times 10^6 , \\text{Pa} ) (max shear stress), - ( \\sigma\_{max} = 200 \\times 10^6 , \\text{Pa} ) (max normal stress), - ( C_w = 209600 , \\text{$/m}^3 ) (welding cost factor), - ( C_s = 0.7 , \\text{$/kg} ) (price of HRC steel), - ( \\rho_s = 7850 , \\text{kg/m}^3 ) (steel density), - ( C_b = 0.7 \\times 7850 , \\text{$/m}^3 ) (beam material cost factor), - ( K = 2 ) (cantilever beam coefficient), - ( \\pi = 3.141592653589793 ) (constant for calculations), - ( \\delta_t = 0.045 ) (tolerance factor for calculations). Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------------------------------------------------------------------------------ | | `Problem` | `Problem` | An instance of the multiobjective cantilever welded beam optimization problem using an equilateral T-beam cross-section. | Source code in `desdeo/problem/testproblems/mcwb_problem.py` ``` def mcwb_equilateral_tbeam_problem() -> Problem: r"""Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem using an equilateral T-beam cross-section. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, \( f_1 = W_c + B_c \), where \( W_c \) is the weld cost and \( B_c \) is the beam cost. 2. Minimize the deflection of the beam, \( f_2 = \frac{P L^3}{3 E I_x} \), where \( P \) is the applied load, \( L \) is the beam length, \( E \) is the Young's modulus, and \( I_x \) is the moment of inertia. Constraints: 1. Shear stress constraint: \( \tau \leq \tau_{max} \), where \( \tau \) is the combined shear stress and \( \tau_{max} \) is the maximum shear stress. 2. Normal stress constraint: \( \sigma_x \leq \sigma_{max} \), where \( \sigma_x \) is the bending stress and \( \sigma_{max} \) is the maximum allowable normal stress. 3. Buckling constraint: \( P \leq P_c \), where \( P_c \) is the critical buckling load. 4. Weld height constraint: \( x_1 \leq x_4 \), ensuring that the weld height \( x_1 \) is less than or equal to the flange/web thickness \( x_4 \). 5. Flange thickness constraint: \( x_4 \geq x_3 \), ensuring that the flange thickness \( x_4 \) is greater than or equal to the beam height \( x_3 \). Where: - \( x_1 \) is the weld height. - \( x_2 \) is the weld length. - \( x_3 \) is the beam height. - \( x_4 \) is the beam thickness (flange/web thickness). The parameters are defined as: - \( P = 30000 \, \text{N} \) (load), - \( L = 0.5 \, \text{m} \) (beam length), - \( E = 200 \times 10^9 \, \text{Pa} \) (Young's modulus), - \( \tau_{max} = 95 \times 10^6 \, \text{Pa} \) (max shear stress), - \( \sigma_{max} = 200 \times 10^6 \, \text{Pa} \) (max normal stress), - \( C_w = 209600 \, \text{\$/m}^3 \) (welding cost factor), - \( C_s = 0.7 \, \text{\$/kg} \) (price of HRC steel), - \( \rho_s = 7850 \, \text{kg/m}^3 \) (steel density), - \( C_b = 0.7 \times 7850 \, \text{\$/m}^3 \) (beam material cost factor), - \( K = 2 \) (cantilever beam coefficient), - \( \pi = 3.141592653589793 \) (constant for calculations), - \( \delta_t = 0.045 \) (tolerance factor for calculations). Returns: Problem: An instance of the multiobjective cantilever welded beam optimization problem using an equilateral T-beam cross-section. """ # Variables variables = [ Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.005, upperbound=0.25 ), # weld height Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.3 ), # weld length Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.25 ), # beam height Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=0.005, upperbound=0.25 ), # beam thickness (flange/web thickness) ] # Constants constants = CONSTANTS # Extra Functions (Intermediate Calculations) extra_functions = [ ExtraFunction( name="cross_section_area", symbol="A", func="x_4 * x_3 + (x_3 - x_4) * x_4", # t * h + (h - t) * t ), ExtraFunction( name="moment_of_inertia", symbol="I_x", func="(x_4 * x_3 ** 3) / 12 + ((x_3 - x_4) * x_4 ** 3) / 12" ), *EXTRAFUNCTION, ] # Objectives (minimize cost, minimize deflection) objectives = OBJECTIVES # Constraints constraints = [ *CONSTRAINTS, Constraint( name="g_4", symbol="g_4", cons_type=ConstraintTypeEnum.LTE, func="(x_1 - x_4) / (0.25 - 0.005)", # weld height <= flange thickness ), Constraint( name="g_5", symbol="g_5", cons_type=ConstraintTypeEnum.LTE, func="(x_4 - x_3) / (0.25 - 0.005)", # flange thickness >= beam height ), ] return Problem( name="MCWB Equilateral T-Beam", description="Multiobjective optimization of a welded T-beam with an equilateral cross-section.", constants=constants, variables=variables, extra_funcs=extra_functions, objectives=objectives, constraints=constraints, ) ``` ### mcwb_hollow_rectangular_problem ``` mcwb_hollow_rectangular_problem() -> Problem ``` Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem using a hollow rectangular cross-section. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, ( f_1 = W_c + B_c ), where ( W_c ) is the weld cost and ( B_c ) is the beam cost. 1. Minimize the deflection of the beam, ( f_2 = \\frac{P L^3}{3 E I_x} ), where ( P ) is the applied load, ( L ) is the beam length, ( E ) is the Young's modulus, and ( I_x ) is the moment of inertia. Constraints: 1. Shear stress constraint: ( \\tau \\leq \\tau\_{max} ), where ( \\tau ) is the combined shear stress and ( \\tau\_{max} ) is the maximum shear stress. 1. Normal stress constraint: ( \\sigma_x \\leq \\sigma\_{max} ), where ( \\sigma_x ) is the bending stress and ( \\sigma\_{max} ) is the maximum allowable normal stress. 1. Buckling constraint: ( P \\leq P_c ), where ( P_c ) is the critical buckling load. 1. Weld height constraint: ( x_1 \\leq x_4 ), ensuring that the weld height ( x_1 ) is less than or equal to the flange thickness ( x_4 ). 1. Wall thickness constraint: ( t \\geq h ), where ( t ) is the wall thickness and ( h ) is the outer height. Where: - ( x_1 ) is the weld height. - ( x_2 ) is the weld length. - ( x_3 ) is the outer height of the beam. - ( x_4 ) is the outer width of the beam. - ( x_5 ) is the wall thickness of the hollow beam. The parameters are defined as: - ( P = 30000 , \\text{N} ) (load), - ( L = 0.5 , \\text{m} ) (beam length), - ( E = 200 \\times 10^9 , \\text{Pa} ) (Young's modulus), - ( \\tau\_{max} = 95 \\times 10^6 , \\text{Pa} ) (max shear stress), - ( \\sigma\_{max} = 200 \\times 10^6 , \\text{Pa} ) (max normal stress), - ( C_w = 209600 , \\text{$/m}^3 ) (welding cost factor), - ( C_s = 0.7 , \\text{$/kg} ) (price of HRC steel), - ( \\rho_s = 7850 , \\text{kg/m}^3 ) (steel density), - ( C_b = 0.7 \\times 7850 , \\text{$/m}^3 ) (beam material cost factor), - ( K = 2 ) (cantilever beam coefficient), - ( \\pi = 3.141592653589793 ) (constant for calculations), - ( \\delta_t = 0.045 ) (tolerance factor for calculations). Returns: | Name | Type | Description | | --------- | --------- | ----------------------------------------------------------------------------------------------------------------------- | | `Problem` | `Problem` | An instance of the multiobjective cantilever welded beam optimization problem using a hollow rectangular cross-section. | Source code in `desdeo/problem/testproblems/mcwb_problem.py` ``` def mcwb_hollow_rectangular_problem() -> Problem: r"""Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem using a hollow rectangular cross-section. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, \( f_1 = W_c + B_c \), where \( W_c \) is the weld cost and \( B_c \) is the beam cost. 2. Minimize the deflection of the beam, \( f_2 = \frac{P L^3}{3 E I_x} \), where \( P \) is the applied load, \( L \) is the beam length, \( E \) is the Young's modulus, and \( I_x \) is the moment of inertia. Constraints: 1. Shear stress constraint: \( \tau \leq \tau_{max} \), where \( \tau \) is the combined shear stress and \( \tau_{max} \) is the maximum shear stress. 2. Normal stress constraint: \( \sigma_x \leq \sigma_{max} \), where \( \sigma_x \) is the bending stress and \( \sigma_{max} \) is the maximum allowable normal stress. 3. Buckling constraint: \( P \leq P_c \), where \( P_c \) is the critical buckling load. 4. Weld height constraint: \( x_1 \leq x_4 \), ensuring that the weld height \( x_1 \) is less than or equal to the flange thickness \( x_4 \). 5. Wall thickness constraint: \( t \geq h \), where \( t \) is the wall thickness and \( h \) is the outer height. Where: - \( x_1 \) is the weld height. - \( x_2 \) is the weld length. - \( x_3 \) is the outer height of the beam. - \( x_4 \) is the outer width of the beam. - \( x_5 \) is the wall thickness of the hollow beam. The parameters are defined as: - \( P = 30000 \, \text{N} \) (load), - \( L = 0.5 \, \text{m} \) (beam length), - \( E = 200 \times 10^9 \, \text{Pa} \) (Young's modulus), - \( \tau_{max} = 95 \times 10^6 \, \text{Pa} \) (max shear stress), - \( \sigma_{max} = 200 \times 10^6 \, \text{Pa} \) (max normal stress), - \( C_w = 209600 \, \text{\$/m}^3 \) (welding cost factor), - \( C_s = 0.7 \, \text{\$/kg} \) (price of HRC steel), - \( \rho_s = 7850 \, \text{kg/m}^3 \) (steel density), - \( C_b = 0.7 \times 7850 \, \text{\$/m}^3 \) (beam material cost factor), - \( K = 2 \) (cantilever beam coefficient), - \( \pi = 3.141592653589793 \) (constant for calculations), - \( \delta_t = 0.045 \) (tolerance factor for calculations). Returns: Problem: An instance of the multiobjective cantilever welded beam optimization problem using a hollow rectangular cross-section. """ # Constants constants = CONSTANTS # Variables variables = [ Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.005, upperbound=0.15 ), # weld height Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.3 ), # weld length Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.3 ), # outer height Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.15 ), # outer width Variable( name="x_5", symbol="x_5", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.03 ), # wall thickness ] # Extra Functions extra_functions = [ ExtraFunction(name="cross_section_area", symbol="A", func="(x_4 * x_3) - ((x_4 - 2*x_5) * (x_3 - 2*x_5))"), ExtraFunction( name="moment_of_inertia", symbol="I_x", func="((x_4 * x_3**3)/12) - (((x_4 - 2*x_5) * (x_3 - 2*x_5)**3)/12)" ), *EXTRAFUNCTION, ] # Objectives objectives = OBJECTIVES # Constraints constraints = [ *CONSTRAINTS, Constraint( name="g_4", symbol="g_4", cons_type=ConstraintTypeEnum.LTE, func="(x_1 - x_4) / (0.15 - 0.005)", # weld height <= beam width, normalised by the weld height range ), Constraint( name="g_5", symbol="g_5", cons_type=ConstraintTypeEnum.LTE, func="(x_5 - x_3 / 2) / (0.03 - 0.01)", # wall thickness <= half the beam height ), Constraint( name="g_6", symbol="g_6", cons_type=ConstraintTypeEnum.LTE, func="(x_5 - x_4 / 2) / (0.03 - 0.01)", # wall thickness <= half the beam width ), ] return Problem( name="MCWB Hollow Rectangular", description="Multiobjective optimization of a welded beam with hollow rectangular cross-section.", constants=constants, variables=variables, extra_funcs=extra_functions, objectives=objectives, constraints=constraints, ) ``` ### mcwb_ragsdell1976_problem ``` mcwb_ragsdell1976_problem() -> Problem ``` Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem based on the framework proposed by Ragsdell (1976). This problem involves optimizing the design of a welded cantilever beam considering welding costs, material costs, and stress constraints. The goal is to minimize both the total cost and the deflection of the beam, while adhering to the given constraints on material properties, geometry, and loading conditions. Objectives: 1. Minimize the total cost, ( f_1 = W_c + B_c ), where: - ( W_c ) is the weld cost, calculated as the sum of welding labor cost and material cost. - ( B_c ) is the beam material cost, based on the beam's dimensions and the cost of the steel used. 2. Minimize the deflection of the beam, ( f_2 = \\frac{P L^3}{3 E I_x} ), where: - ( P ) is the applied load. - ( L ) is the beam length. - ( E ) is the Young's modulus. - ( I_x ) is the moment of inertia of the beam's cross-section. Constraints: 1. **Weld height constraint**: ( x_1 \\leq x_4 ), ensuring that the weld height ( x_1 ) is less than or equal to the beam width ( x_4 ) (flange thickness). 1. The problem also considers the material constraints on maximum shear stress and normal stress, but these are not explicitly listed as constraints in this setup. Where: - ( x_1 ) is the height of the weld. - ( x_2 ) is the length of the weld. - ( x_3 ) is the height of the beam. - ( x_4 ) is the width of the beam. Constants: - ( P = 30000 , \\text{N} ) (load), - ( L = 0.5 , \\text{m} ) (beam length), - ( E = 200 \\times 10^9 , \\text{Pa} ) (Young's modulus), - ( \\tau\_{\\text{max}} = 95 \\times 10^6 , \\text{Pa} ) (maximum shear stress), - ( \\sigma\_{\\text{max}} = 200 \\times 10^6 , \\text{Pa} ) (maximum normal stress), - ( C\_{\\text{wl}} = 1 , \\text{$/in} ) (welding labor cost), - ( C\_{\\text{wm}} = 0.10471 , \\text{$/in} ) (welding material cost), - ( C\_{\\text{w}} = 1 \\times 0.10471 , \\text{$/in} ) (total welding cost), - ( C_s = 0.7 , \\text{$/kg} ) (steel price), - ( \\rho_s = 7850 , \\text{kg/m}^3 ) (steel density), - ( C_b = 0.04811 , \\text{$/in} ) (beam material cost), - ( K = 2 ) (cantilever beam coefficient), - ( \\pi = 3.141592653589793 ) (constant), - ( \\delta_t = 0.05 - 0.005 ) (tolerance factor). Intermediate Functions: 1. **Cross-sectional area**: ( A = x_3 \\times x_4 ). 1. **Moment of inertia**: ( I_x = \\frac{x_4 \\times x_3^3}{12} ), representing the beam's resistance to bending. Returns: | Name | Type | Description | | --------- | --------- | ---------------------------------------------------------------------------------------------------------------- | | `Problem` | `Problem` | An instance of the multiobjective cantilever welded beam optimization problem based on Ragsdell's method (1976). | Source code in `desdeo/problem/testproblems/mcwb_problem.py` ``` def mcwb_ragsdell1976_problem() -> Problem: r"""Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem based on the framework proposed by Ragsdell (1976). This problem involves optimizing the design of a welded cantilever beam considering welding costs, material costs, and stress constraints. The goal is to minimize both the total cost and the deflection of the beam, while adhering to the given constraints on material properties, geometry, and loading conditions. Objectives: 1. Minimize the total cost, \( f_1 = W_c + B_c \), where: - \( W_c \) is the weld cost, calculated as the sum of welding labor cost and material cost. - \( B_c \) is the beam material cost, based on the beam's dimensions and the cost of the steel used. 2. Minimize the deflection of the beam, \( f_2 = \frac{P L^3}{3 E I_x} \), where: - \( P \) is the applied load. - \( L \) is the beam length. - \( E \) is the Young's modulus. - \( I_x \) is the moment of inertia of the beam's cross-section. Constraints: 1. **Weld height constraint**: \( x_1 \leq x_4 \), ensuring that the weld height \( x_1 \) is less than or equal to the beam width \( x_4 \) (flange thickness). 2. The problem also considers the material constraints on maximum shear stress and normal stress, but these are not explicitly listed as constraints in this setup. Where: - \( x_1 \) is the height of the weld. - \( x_2 \) is the length of the weld. - \( x_3 \) is the height of the beam. - \( x_4 \) is the width of the beam. Constants: - \( P = 30000 \, \text{N} \) (load), - \( L = 0.5 \, \text{m} \) (beam length), - \( E = 200 \times 10^9 \, \text{Pa} \) (Young's modulus), - \( \tau_{\text{max}} = 95 \times 10^6 \, \text{Pa} \) (maximum shear stress), - \( \sigma_{\text{max}} = 200 \times 10^6 \, \text{Pa} \) (maximum normal stress), - \( C_{\text{wl}} = 1 \, \text{\$/in} \) (welding labor cost), - \( C_{\text{wm}} = 0.10471 \, \text{\$/in} \) (welding material cost), - \( C_{\text{w}} = 1 \times 0.10471 \, \text{\$/in} \) (total welding cost), - \( C_s = 0.7 \, \text{\$/kg} \) (steel price), - \( \rho_s = 7850 \, \text{kg/m}^3 \) (steel density), - \( C_b = 0.04811 \, \text{\$/in} \) (beam material cost), - \( K = 2 \) (cantilever beam coefficient), - \( \pi = 3.141592653589793 \) (constant), - \( \delta_t = 0.05 - 0.005 \) (tolerance factor). Intermediate Functions: 1. **Cross-sectional area**: \( A = x_3 \times x_4 \). 2. **Moment of inertia**: \( I_x = \frac{x_4 \times x_3^3}{12} \), representing the beam's resistance to bending. Returns: Problem: An instance of the multiobjective cantilever welded beam optimization problem based on Ragsdell's method (1976). """ # Variables (decision variables: weld height, weld length, beam height, beam width) variables = [ Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.125, upperbound=5 ), # height of weld [in] Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.1, upperbound=10 ), # length of weld [in] Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0.1, upperbound=10 ), # height of beam [in] Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=0.1, upperbound=5 ), # width of beam [in] ] constants = [ Constant(name="P", symbol="P", value=6000), # Load [lb] Constant(name="L", symbol="L", value=14), # Beam length [in] Constant(name="E", symbol="E", value=30e6), # Young's modulus [psi] Constant(name="tau_max", symbol="tau_max", value=13600), # Max shear stress [psi] Constant(name="sigma_max", symbol="sigma_max", value=30000), # Max normal stress [psi] Constant(name="C_wl", symbol="C_wl", value=1), # Welding labor cost [$/in^3] Constant(name="C_wm", symbol="C_wm", value=0.10471), # Welding material cost [$/in^3] Constant(name="C_w", symbol="C_w", value=1 + 0.10471), # Total welding cost [$/in^3] Constant(name="C_b", symbol="C_b", value=0.04811), # Beam material cost [$/in^3] Constant(name="K", symbol="K", value=2), # Cantilever beam coefficient Constant(name="pi", symbol="pi", value=3.141592653589793), Constant(name="delta_t", symbol="delta_t", value=0.05 - 0.005), ] # Extra Functions (Intermediate Calculations) extra_functions = [ ExtraFunction(name="cross_section_area", symbol="A", func="x_3 * x_4"), # A = h * b ExtraFunction(name="moment_of_inertia", symbol="I_x", func="(x_4 * x_3**3) / 12"), # I_x = (b * h³) / 12 *EXTRAFUNCTION, ] # Objectives (minimize cost, minimize deflection) objectives = OBJECTIVES # NO DUMMY CONSTRAINTS # Constraints extra_functions = [ ExtraFunction(name="cross_section_area", symbol="A", func="x_3 * x_4"), # A = h * b ExtraFunction(name="moment_of_inertia", symbol="I_x", func="(x_4 * x_3**3) / 12"), # I_x = (b * h³) / 12 *EXTRAFUNCTION, ] # Constraints constraints = [ *CONSTRAINTS, Constraint( name="g_4", symbol="g_4", cons_type=ConstraintTypeEnum.LTE, func="(x_1 - x_4) / (5 - 0.125)", # weld height <= beam width, normalised by the weld height range ), ] return Problem( name="MCWB Ragsdell1976", description=( "Optimization of a welded beam based on Ragsdell's method (1976), " "considering welding and material costs and stress constraints." ), constants=constants, variables=variables, extra_funcs=extra_functions, objectives=objectives, constraints=constraints, ) ``` ### mcwb_solid_rectangular_problem ``` mcwb_solid_rectangular_problem() -> Problem ``` Defines the multiobjective cantilever welded beam (MCWB) optimization problem. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, ( f_1 = W_c + B_c ), where ( W_c ) is the weld cost and ( B_c ) is the beam cost. 1. Minimize the deflection of the beam, ( f_2 = \\frac{P L^3}{3 E I_x} ), where ( P ) is the applied load, ( L ) is the beam length, ( E ) is the Young's modulus, and ( I_x ) is the moment of inertia. Constraints: 1. Shear stress constraint: ( \\tau \\leq \\tau\_{max} ), where ( \\tau ) is the combined shear stress and ( \\tau\_{max} ) is the maximum shear stress. 1. Normal stress constraint: ( \\sigma_x \\leq \\sigma\_{max} ), where ( \\sigma_x ) is the bending stress and ( \\sigma\_{max} ) is the maximum allowable normal stress. 1. Buckling constraint: ( P \\leq P_c ), where ( P_c ) is the critical buckling load. 1. Weld height constraint: ( x_1 \\leq x_4 ), ensuring that the weld height ( x_1 ) is less than or equal to the flange thickness ( x_4 ). Where: - ( x_1 ) is the weld height. - ( x_2 ) is the weld length. - ( x_3 ) is the beam height. - ( x_4 ) is the beam width. The parameters are defined as: - ( P = 30000 , \\text{N} ) (load), - ( L = 0.5 , \\text{m} ) (beam length), - ( E = 200 \\times 10^9 , \\text{Pa} ) (Young's modulus), - ( \\tau\_{max} = 95 \\times 10^6 , \\text{Pa} ) (max shear stress), - ( \\sigma\_{max} = 200 \\times 10^6 , \\text{Pa} ) (max normal stress), - ( C_w = 209600 , \\text{$/m}^3 ) (welding cost factor), - ( C_s = 0.7 , \\text{$/kg} ) (price of HRC steel), - ( \\rho_s = 7850 , \\text{kg/m}^3 ) (steel density), - ( C_b = 0.7 \\times 7850 , \\text{$/m}^3 ) (beam material cost factor), - ( K = 2 ) (cantilever beam coefficient), - ( \\pi = 3.141592653589793 ) (constant for calculations), - ( \\delta_t = 0.045 ) (tolerance factor for calculations). Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------------------------------------ | | `Problem` | `Problem` | An instance of the multiobjective cantilever welded beam optimization problem. | Source code in `desdeo/problem/testproblems/mcwb_problem.py` ``` def mcwb_solid_rectangular_problem() -> Problem: r"""Defines the multiobjective cantilever welded beam (MCWB) optimization problem. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, \( f_1 = W_c + B_c \), where \( W_c \) is the weld cost and \( B_c \) is the beam cost. 2. Minimize the deflection of the beam, \( f_2 = \frac{P L^3}{3 E I_x} \), where \( P \) is the applied load, \( L \) is the beam length, \( E \) is the Young's modulus, and \( I_x \) is the moment of inertia. Constraints: 1. Shear stress constraint: \( \tau \leq \tau_{max} \), where \( \tau \) is the combined shear stress and \( \tau_{max} \) is the maximum shear stress. 2. Normal stress constraint: \( \sigma_x \leq \sigma_{max} \), where \( \sigma_x \) is the bending stress and \( \sigma_{max} \) is the maximum allowable normal stress. 3. Buckling constraint: \( P \leq P_c \), where \( P_c \) is the critical buckling load. 4. Weld height constraint: \( x_1 \leq x_4 \), ensuring that the weld height \( x_1 \) is less than or equal to the flange thickness \( x_4 \). Where: - \( x_1 \) is the weld height. - \( x_2 \) is the weld length. - \( x_3 \) is the beam height. - \( x_4 \) is the beam width. The parameters are defined as: - \( P = 30000 \, \text{N} \) (load), - \( L = 0.5 \, \text{m} \) (beam length), - \( E = 200 \times 10^9 \, \text{Pa} \) (Young's modulus), - \( \tau_{max} = 95 \times 10^6 \, \text{Pa} \) (max shear stress), - \( \sigma_{max} = 200 \times 10^6 \, \text{Pa} \) (max normal stress), - \( C_w = 209600 \, \text{\$/m}^3 \) (welding cost factor), - \( C_s = 0.7 \, \text{\$/kg} \) (price of HRC steel), - \( \rho_s = 7850 \, \text{kg/m}^3 \) (steel density), - \( C_b = 0.7 \times 7850 \, \text{\$/m}^3 \) (beam material cost factor), - \( K = 2 \) (cantilever beam coefficient), - \( \pi = 3.141592653589793 \) (constant for calculations), - \( \delta_t = 0.045 \) (tolerance factor for calculations). Returns: Problem: An instance of the multiobjective cantilever welded beam optimization problem. """ # Variables variables = [ Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.005, upperbound=0.15 ), # height of weld Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.3 ), # length of weld Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.3 ), # height of beam Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.15 ), # width of beam ] # Constants constants = CONSTANTS # Extra Functions (Intermediate Calculations) extra_functions = [ ExtraFunction(name="cross_section_area", symbol="A", func="x_3 * x_4"), # A = h * b ExtraFunction(name="moment_of_inertia", symbol="I_x", func="(x_4 * x_3**3) / 12"), # I_x = (b * h³) / 12 *EXTRAFUNCTION, ] # Objectives (minimize cost, minimize deflection) objectives = OBJECTIVES # NO DUMMY CONSTRAINTS # Constraints constraints = [ *CONSTRAINTS, Constraint( name="g_4", symbol="g_4", cons_type=ConstraintTypeEnum.LTE, func="(x_1 - x_4) / (0.15 - 0.005)", # weld height <= beam width, normalised by the weld height range ), ] return Problem( name="MCWB Solid Rectangular", description="Multiobjective optimization of a welded beam using a solid rectangular cross-section.", constants=constants, variables=variables, extra_funcs=extra_functions, objectives=objectives, constraints=constraints, ) ``` ### mcwb_square_channel_problem ``` mcwb_square_channel_problem() -> Problem ``` Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem using a square channel cross-section. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, ( f_1 = W_c + B_c ), where ( W_c ) is the weld cost and ( B_c ) is the beam cost. 1. Minimize the deflection of the beam, ( f_2 = \\frac{P L^3}{3 E I_x} ), where ( P ) is the applied load, ( L ) is the beam length, ( E ) is the Young's modulus, and ( I_x ) is the moment of inertia. Constraints: 1. Weld height constraint: ( x_1 \\leq x_4 ), ensuring that the weld height ( x_1 ) is less than or equal to the flange thickness ( x_4 ). 1. Beam width constraint: ( x_4 \\geq x_3 ), ensuring that the beam width ( x_4 ) is greater than or equal to the beam height ( x_3 ). 1. Web thickness constraint: ( x_6 \\geq \\frac{x_3}{2} ), ensuring that the web thickness ( x_6 ) is greater than or equal to half the beam height ( x_3 ). 1. Flange thickness constraint: ( x_5 \\geq x_4 ), ensuring that the flange thickness ( x_5 ) is greater than or equal to the beam width ( x_4 ). Where: - ( x_1 ) is the weld height. - ( x_2 ) is the weld length. - ( x_3 ) is the beam height. - ( x_4 ) is the beam width. - ( x_5 ) is the flange thickness. - ( x_6 ) is the web thickness. The parameters are defined as: - ( P = 30000 , \\text{N} ) (load), - ( L = 0.5 , \\text{m} ) (beam length), - ( E = 200 \\times 10^9 , \\text{Pa} ) (Young's modulus), - ( \\tau\_{max} = 95 \\times 10^6 , \\text{Pa} ) (max shear stress), - ( \\sigma\_{max} = 200 \\times 10^6 , \\text{Pa} ) (max normal stress), - ( C_w = 209600 , \\text{$/m}^3 ) (welding cost factor), - ( C_s = 0.7 , \\text{$/kg} ) (price of HRC steel), - ( \\rho_s = 7850 , \\text{kg/m}^3 ) (steel density), - ( C_b = 0.7 \\times 7850 , \\text{$/m}^3 ) (beam material cost factor), - ( K = 2 ) (cantilever beam coefficient), - ( \\pi = 3.141592653589793 ) (constant for calculations), - ( \\delta_t = 0.045 ) (tolerance factor for calculations). Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------------------------------------------------------------------------- | | `Problem` | `Problem` | An instance of the multiobjective cantilever welded beam optimization problem using a square channel cross-section. | Source code in `desdeo/problem/testproblems/mcwb_problem.py` ``` def mcwb_square_channel_problem() -> Problem: r"""Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem using a square channel cross-section. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, \( f_1 = W_c + B_c \), where \( W_c \) is the weld cost and \( B_c \) is the beam cost. 2. Minimize the deflection of the beam, \( f_2 = \frac{P L^3}{3 E I_x} \), where \( P \) is the applied load, \( L \) is the beam length, \( E \) is the Young's modulus, and \( I_x \) is the moment of inertia. Constraints: 1. Weld height constraint: \( x_1 \leq x_4 \), ensuring that the weld height \( x_1 \) is less than or equal to the flange thickness \( x_4 \). 2. Beam width constraint: \( x_4 \geq x_3 \), ensuring that the beam width \( x_4 \) is greater than or equal to the beam height \( x_3 \). 3. Web thickness constraint: \( x_6 \geq \frac{x_3}{2} \), ensuring that the web thickness \( x_6 \) is greater than or equal to half the beam height \( x_3 \). 4. Flange thickness constraint: \( x_5 \geq x_4 \), ensuring that the flange thickness \( x_5 \) is greater than or equal to the beam width \( x_4 \). Where: - \( x_1 \) is the weld height. - \( x_2 \) is the weld length. - \( x_3 \) is the beam height. - \( x_4 \) is the beam width. - \( x_5 \) is the flange thickness. - \( x_6 \) is the web thickness. The parameters are defined as: - \( P = 30000 \, \text{N} \) (load), - \( L = 0.5 \, \text{m} \) (beam length), - \( E = 200 \times 10^9 \, \text{Pa} \) (Young's modulus), - \( \tau_{max} = 95 \times 10^6 \, \text{Pa} \) (max shear stress), - \( \sigma_{max} = 200 \times 10^6 \, \text{Pa} \) (max normal stress), - \( C_w = 209600 \, \text{\$/m}^3 \) (welding cost factor), - \( C_s = 0.7 \, \text{\$/kg} \) (price of HRC steel), - \( \rho_s = 7850 \, \text{kg/m}^3 \) (steel density), - \( C_b = 0.7 \times 7850 \, \text{\$/m}^3 \) (beam material cost factor), - \( K = 2 \) (cantilever beam coefficient), - \( \pi = 3.141592653589793 \) (constant for calculations), - \( \delta_t = 0.045 \) (tolerance factor for calculations). Returns: Problem: An instance of the multiobjective cantilever welded beam optimization problem using a square channel cross-section. """ # Variables variables = [ Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.005, upperbound=0.15 ), # weld height (a) Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.3 ), # weld length (l) Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.25 ), # beam height (h) Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.15 ), # beam width (b) Variable( name="x_5", symbol="x_5", variable_type=VariableTypeEnum.real, lowerbound=0.0075, upperbound=0.03 ), # flange thickness (t) Variable( name="x_6", symbol="x_6", variable_type=VariableTypeEnum.real, lowerbound=0.0075, upperbound=0.03 ), # web thickness (u) ] # Constants constants = CONSTANTS # Extra Functions (Intermediate Calculations) extra_functions = [ ExtraFunction(name="cross_section_area", symbol="A", func="(x_3 * x_4) - ((x_4 - x_5) * (x_3 - 2 * x_6))"), ExtraFunction( name="moment_of_inertia", symbol="I_x", func="(x_4 * x_3 ** 3) / 12 - ((x_4 - x_5) * (x_3 - 2 * x_6) ** 3) / 12", ), *EXTRAFUNCTION, ] # Objectives (minimize cost, minimize deflection, etc.) objectives = OBJECTIVES # Constraints constraints = [ *CONSTRAINTS, # Weld height constraint (g_4) Constraint( name="g_4", symbol="g_4", cons_type=ConstraintTypeEnum.LTE, func="(x_1 - x_4) / (0.15 - 0.005)", # weld height <= beam width, normalised by the weld height range ), # Cross-section geometric constraints (g_5 and g_6) Constraint( name="g_5", symbol="g_5", cons_type=ConstraintTypeEnum.LTE, func="(x_6 - x_3 / 2) / (0.03 - 0.0075)", # flange thickness <= half the beam height ), Constraint( name="g_6", symbol="g_6", cons_type=ConstraintTypeEnum.LTE, func="(x_5 - x_4) / (0.03 - 0.0075)", # web thickness <= beam width ), ] return Problem( name="MCWB Square Channel", description=( "Multiobjective optimization of a welded square channel beam with constraints on geometry " "and load-bearing capacity." ), constants=constants, variables=variables, extra_funcs=extra_functions, objectives=objectives, constraints=constraints, ) ``` ### mcwb_tapered_channel_problem ``` mcwb_tapered_channel_problem() -> Problem ``` Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem using a tapered channel cross-section. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, ( f_1 = W_c + B_c ), where ( W_c ) is the weld cost and ( B_c ) is the beam cost. 1. Minimize the deflection of the beam, ( f_2 = \\frac{P L^3}{3 E I_x} ), where ( P ) is the applied load, ( L ) is the beam length, ( E ) is the Young's modulus, and ( I_x ) is the moment of inertia. Constraints: 1. Weld height constraint: ( x_1 \\leq x_5 ), ensuring that the weld height ( x_1 ) is less than or equal to the outer flange thickness ( x_5 ). 1. Beam width constraint: ( x_4 \\geq x_3 ), ensuring that the beam width ( x_4 ) is greater than or equal to the beam height ( x_3 ). 1. Inner flange height constraint: ( x_6 \\geq \\frac{x_3}{2} ), ensuring that the inner flange height ( x_6 ) is greater than or equal to half the beam height ( x_3 ). 1. Web thickness constraint: ( x_7 \\leq x_4 ), ensuring that the web thickness ( x_7 ) is less than or equal to the beam width ( x_4 ). 1. Outer flange thickness constraint: ( x_5 \\leq x_6 ), ensuring that the outer flange thickness ( x_5 ) is less than or equal to the inner flange thickness ( x_6 ). Where: - ( x_1 ) is the weld height. - ( x_2 ) is the weld length. - ( x_3 ) is the beam height. - ( x_4 ) is the beam width. - ( x_5 ) is the outer flange thickness. - ( x_6 ) is the inner flange thickness. - ( x_7 ) is the web thickness. The parameters are defined as: - ( P = 30000 , \\text{N} ) (load), - ( L = 0.5 , \\text{m} ) (beam length), - ( E = 200 \\times 10^9 , \\text{Pa} ) (Young's modulus), - ( \\tau\_{max} = 95 \\times 10^6 , \\text{Pa} ) (max shear stress), - ( \\sigma\_{max} = 200 \\times 10^6 , \\text{Pa} ) (max normal stress), - ( C_w = 209600 , \\text{$/m}^3 ) (welding cost factor), - ( C_s = 0.7 , \\text{$/kg} ) (price of HRC steel), - ( \\rho_s = 7850 , \\text{kg/m}^3 ) (steel density), - ( C_b = 0.7 \\times 7850 , \\text{$/m}^3 ) (beam material cost factor), - ( K = 2 ) (cantilever beam coefficient), - ( \\pi = 3.141592653589793 ) (constant for calculations), - ( \\delta_t = 0.045 ) (tolerance factor for calculations). Returns: | Name | Type | Description | | --------- | --------- | -------------------------------------------------------------------------------------------------------------------- | | `Problem` | `Problem` | An instance of the multiobjective cantilever welded beam optimization problem using a tapered channel cross-section. | Source code in `desdeo/problem/testproblems/mcwb_problem.py` ``` def mcwb_tapered_channel_problem() -> Problem: r"""Defines the multiobjective cantilever welded beam (MCWB) optimization problem... Defines the multiobjective cantilever welded beam (MCWB) optimization problem using a tapered channel cross-section. The objective functions and constraints for the MCWB design problem are defined as follows: Objectives: 1. Minimize the total cost, \( f_1 = W_c + B_c \), where \( W_c \) is the weld cost and \( B_c \) is the beam cost. 2. Minimize the deflection of the beam, \( f_2 = \frac{P L^3}{3 E I_x} \), where \( P \) is the applied load, \( L \) is the beam length, \( E \) is the Young's modulus, and \( I_x \) is the moment of inertia. Constraints: 1. Weld height constraint: \( x_1 \leq x_5 \), ensuring that the weld height \( x_1 \) is less than or equal to the outer flange thickness \( x_5 \). 2. Beam width constraint: \( x_4 \geq x_3 \), ensuring that the beam width \( x_4 \) is greater than or equal to the beam height \( x_3 \). 3. Inner flange height constraint: \( x_6 \geq \frac{x_3}{2} \), ensuring that the inner flange height \( x_6 \) is greater than or equal to half the beam height \( x_3 \). 4. Web thickness constraint: \( x_7 \leq x_4 \), ensuring that the web thickness \( x_7 \) is less than or equal to the beam width \( x_4 \). 5. Outer flange thickness constraint: \( x_5 \leq x_6 \), ensuring that the outer flange thickness \( x_5 \) is less than or equal to the inner flange thickness \( x_6 \). Where: - \( x_1 \) is the weld height. - \( x_2 \) is the weld length. - \( x_3 \) is the beam height. - \( x_4 \) is the beam width. - \( x_5 \) is the outer flange thickness. - \( x_6 \) is the inner flange thickness. - \( x_7 \) is the web thickness. The parameters are defined as: - \( P = 30000 \, \text{N} \) (load), - \( L = 0.5 \, \text{m} \) (beam length), - \( E = 200 \times 10^9 \, \text{Pa} \) (Young's modulus), - \( \tau_{max} = 95 \times 10^6 \, \text{Pa} \) (max shear stress), - \( \sigma_{max} = 200 \times 10^6 \, \text{Pa} \) (max normal stress), - \( C_w = 209600 \, \text{\$/m}^3 \) (welding cost factor), - \( C_s = 0.7 \, \text{\$/kg} \) (price of HRC steel), - \( \rho_s = 7850 \, \text{kg/m}^3 \) (steel density), - \( C_b = 0.7 \times 7850 \, \text{\$/m}^3 \) (beam material cost factor), - \( K = 2 \) (cantilever beam coefficient), - \( \pi = 3.141592653589793 \) (constant for calculations), - \( \delta_t = 0.045 \) (tolerance factor for calculations). Returns: Problem: An instance of the multiobjective cantilever welded beam optimization problem using a tapered channel cross-section. """ # Variables variables = [ Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.005, upperbound=0.15 ), # weld height (a) Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.3 ), # weld length (l) Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.2 ), # beam height (h) Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.15 ), # beam width (b) Variable( name="x_5", symbol="x_5", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.03 ), # flange thickness outer (u) Variable( name="x_6", symbol="x_6", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=2 * 0.03 ), # flange thickness inner (v) Variable( name="x_7", symbol="x_7", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.03 ), # web thickness (t) ] # Constants constants = CONSTANTS # Extra Functions (Intermediate Calculations) extra_functions = [ # b_inner: the inner width of the flange (b - t) ExtraFunction(name="b_inner", symbol="b_inner", func="x_4 - x_5"), # A_web: area of the web (h * t) ExtraFunction(name="A_web", symbol="A_web", func="x_3 * x_5"), # A_flange: area of the flange (b_inner * (u + v)) ExtraFunction(name="A_flange", symbol="A_flange", func="b_inner * (x_6 + x_7)"), # Total cross-sectional area (A = A_web + A_flange) ExtraFunction(name="cross_section_area", symbol="A", func="A_web + A_flange"), # Moment of inertia for the outer rectangle (Ix_rectangle) ExtraFunction(name="Ix_rectangle", symbol="Ix_rectangle", func="(x_4 * x_3 ** 3) / 12"), ExtraFunction(name="flange_to_flange_outer", symbol="flange_to_flange_outer", func="x_3 - 2 * x_6"), ExtraFunction(name="flange_to_flange_inner", symbol="flange_to_flange_inner", func="x_3 - 2 * x_7"), ExtraFunction( name="slope_flange", symbol="slope_flange", func="(flange_to_flange_outer - flange_to_flange_inner) / 2 * (x_4 - x_5)", ), # Moment of inertia for the outer flange (Ix_flange_outer) ExtraFunction( name="Ix_flange_outer", symbol="Ix_flange_outer", func="(flange_to_flange_outer ** 4 / 8 * slope_flange) / 12", ), # Moment of inertia for the inner flange (Ix_flange_inner) ExtraFunction( name="Ix_flange_inner", symbol="Ix_flange_inner", func="(flange_to_flange_inner) ** 4 / 8 * slope_flange / 12", ), ExtraFunction(name="Ix_flange", symbol="Ix_flange", func="Ix_flange_outer - Ix_flange_inner"), # Total moment of inertia: Ix = Ix_rectangle + Ix_flange_outer - Ix_flange_inner ExtraFunction(name="moment_of_inertia", symbol="I_x", func="Ix_rectangle + Ix_flange"), *EXTRAFUNCTION, ] # Objectives (minimize cost, minimize deflection, etc.) objectives = OBJECTIVES # Constraints constraints = [ *CONSTRAINTS, # Weld height constraint (g_4) Constraint( name="g_4", symbol="g_4", cons_type=ConstraintTypeEnum.LTE, func="(x_1 - x_4) / (0.15 - 0.005)", # weld height <= beam width, normalised by the weld height range ), # Cross-section geometric constraints (g_5 to g_7), normalised by the thickness ranges Constraint( name="g_5", symbol="g_5", cons_type=ConstraintTypeEnum.LTE, func="(x_7 - x_3 / 2) / (2 * 0.03 - 0.01)", # inner flange thickness <= half the beam height ), Constraint( name="g_6", symbol="g_6", cons_type=ConstraintTypeEnum.LTE, func="(x_5 - x_4) / (0.03 - 0.01)", # web thickness <= beam width ), Constraint( name="g_7", symbol="g_7", cons_type=ConstraintTypeEnum.LTE, func="(x_6 - x_7) / (2 * 0.03 - 0.01)", # outer flange thickness <= inner flange thickness ), ] return Problem( name="MCWB Tapered Channel", description=( "Multiobjective optimization of a welded tapered channel beam with constraints on geometry " "and load-bearing capacity." ), constants=constants, variables=variables, extra_funcs=extra_functions, objectives=objectives, constraints=constraints, ) ``` ### metallurgical_application ``` metallurgical_application( objectives: tuple[str, ...] | list[str] = MOP_II, *, random_state: int = 0, charpy_temperature: float = DEFAULT_CHARPY_TEMPERATURE, data_dir: Path | None = None, cache_dir: Path | None = None, download: bool = True, ) -> Problem ``` Defines the microalloyed steel design problem of Saini et al. (2023). A steel is designed by choosing the weight per cent of 17 alloying elements. Four of the six objectives -- yield strength, ultimate tensile strength, elongation and Charpy impact energy -- are predicted from the composition by surrogate models fitted to measurement data and are maximised. The other two are analytical and minimised: the carbon equivalent, which stands for how hard the alloy is to weld, and the material cost. [\\begin{align} \\text{CE} &= C + \\frac{Mn + Si}{6} + \\frac{Cr + Mo + V}{5} + \\frac{Cu + Ni}{15} \\ \\text{COST} &= \\sum_i \\text{price}\_i \\cdot c_i \\end{align}] The paper's own two formulations are available as `MOP_I`, all six objectives, and `MOP_II`, which drops the Charpy objective. `MOP_II` is the default, following the paper, which introduces it because "the Charpy surrogate model had a worse accuracy than the other surrogate models". Objective subsets Pass any subset of `OBJECTIVES` to get a different version of the problem. Only the surrogates for the chosen properties are trained, so asking for `("CE", "YS")` does not pay for the models it will not use. **The decision variable bounds depend on which objectives are chosen.** They are the intersection of the composition ranges of the datasets behind the selected surrogate objectives, so dropping a property widens the box, as it does between the paper's MOP-I and MOP-II: "removing this objective also led to an expansion of the bounds of the decision variables (calculated as the bounds of the intersection of the remaining datasets)". The intersection is what keeps every point of the box inside the range each model was fitted on, so no model is asked to extrapolate. When no surrogate objective is selected at all, the intersection of all four datasets is used. A study that compares subsets against each other should know that they therefore do not share a decision space, and that the comparison is between problems, not between objective counts on one problem. Note **Three deviations from the paper, and one from the how-to guide, all deliberate.** The paper selects XGBoost for the tensile strength by cross-validation, at a median (R^2) of 0.8440 against gradient boosting's 0.8437. Gradient boosting is used here instead: the gap is two parts in ten thousand of a quantity whose standard deviation across folds is 0.07, and `xgboost` is not a DESDEO dependency. The paper's Table 3 lists the bounds it used. Five of the seventeen upper bounds computed from the datasets in this repository differ from it -- manganese, nickel, aluminium, boron and copper -- so the data shipped here is not exactly the data the paper's numbers came from. The bounds are computed from the shipped data rather than hard-coded from the table, so that the box always matches the models actually fitted. The paper reports an ideal cost of about 43 USD per kg, which the cost formula above does not reproduce: read as weight per cent times USD per kg, the cheapest point of the box costs well under 1. The paper does not state the unit convention, so the formula is implemented as written and the discrepancy is left visible rather than tuned away. The how-to guide omits the silicon term from the carbon equivalent, uses gradient boosting for the tensile strength, fits every model on all 17 elements, and has neither the Charpy nor the cost objective. This module follows the paper. The training data contains repeated compositions with different measured values -- the same alloy behaves differently after different processing -- so the models cannot interpolate their own training data exactly. The paper's cross-validated (R^2) is 0.75 for yield strength, 0.84 for tensile strength, 0.67 for elongation and 0.44 for the Charpy energy, which is the one to keep in mind when reading results. Data and models The datasets ship with the DESDEO repository but not with the installed package. They are looked for in `data_dir`, then in the repository checkout this module lives in, then in the cache; only if none of those has them are they downloaded from GitHub. Trained models are cached under `$XDG_CACHE_HOME/desdeo/MetallApplication` (or `~/.cache/desdeo/MetallApplication`), keyed by the scikit-learn version, the seed, the Charpy temperature and a digest of the training data. Training them takes a few seconds; later calls load the cache. A cached file that fails to load is discarded and retrained rather than raised, which is what happens when scikit-learn is upgraded under an old pickle. `random_state` is passed to every regressor, so the problem is reproducible for a given seed and scikit-learn version. The how-to guide leaves it unset, and its models therefore differ from run to run. Each model is wrapped in a `CompositionModel`, which selects the elements that model was fitted on and, for the Charpy energy, appends the fixed test temperature. The wrapper is what lets every objective share one 17-element decision vector. Parameters: | Name | Type | Description | Default | | -------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `objectives` | \`tuple[str, ...] | list[str]\` | which objectives to include, as symbols from OBJECTIVES. The order given is the order they appear in. Defaults to MOP_II. | | `random_state` | `int` | the seed the regressors are fitted with. Defaults to 0. | `0` | | `charpy_temperature` | `float` | the temperature in degrees Celsius the Charpy impact energy is evaluated at. Ignored unless CHARPY is among the objectives. Defaults to DEFAULT_CHARPY_TEMPERATURE. | `DEFAULT_CHARPY_TEMPERATURE` | | `data_dir` | \`Path | None\` | a directory to look for the datasets in before anywhere else. Defaults to None. | | `cache_dir` | \`Path | None\` | where to cache datasets and models. Defaults to None, meaning the user cache directory. | | `download` | `bool` | whether the datasets may be fetched from the DESDEO repository when they are not available locally. Defaults to True. | `True` | Raises: | Type | Description | | ------------------- | ------------------------------------------------------------------- | | `ValueError` | if objectives is empty, names an unknown objective, or repeats one. | | `FileNotFoundError` | if a dataset is missing locally and download is False. | | `RuntimeError` | if a dataset has to be downloaded and the download fails. | Returns: | Name | Type | Description | | --------- | --------- | ----------------------------------------------------- | | `Problem` | `Problem` | an instance of the microalloyed steel design problem. | Source code in `desdeo/problem/testproblems/metallurgical_application_problem.py` ``` def metallurgical_application( objectives: tuple[str, ...] | list[str] = MOP_II, *, random_state: int = 0, charpy_temperature: float = DEFAULT_CHARPY_TEMPERATURE, data_dir: Path | None = None, cache_dir: Path | None = None, download: bool = True, ) -> Problem: r"""Defines the microalloyed steel design problem of Saini et al. (2023). A steel is designed by choosing the weight per cent of 17 alloying elements. Four of the six objectives -- yield strength, ultimate tensile strength, elongation and Charpy impact energy -- are predicted from the composition by surrogate models fitted to measurement data and are maximised. The other two are analytical and minimised: the carbon equivalent, which stands for how hard the alloy is to weld, and the material cost. \begin{align} \text{CE} &= C + \frac{Mn + Si}{6} + \frac{Cr + Mo + V}{5} + \frac{Cu + Ni}{15} \\ \text{COST} &= \sum_i \text{price}_i \cdot c_i \end{align} The paper's own two formulations are available as `MOP_I`, all six objectives, and `MOP_II`, which drops the Charpy objective. `MOP_II` is the default, following the paper, which introduces it because "the Charpy surrogate model had a worse accuracy than the other surrogate models". Objective subsets: Pass any subset of `OBJECTIVES` to get a different version of the problem. Only the surrogates for the chosen properties are trained, so asking for `("CE", "YS")` does not pay for the models it will not use. **The decision variable bounds depend on which objectives are chosen.** They are the intersection of the composition ranges of the datasets behind the selected surrogate objectives, so dropping a property widens the box, as it does between the paper's MOP-I and MOP-II: "removing this objective also led to an expansion of the bounds of the decision variables (calculated as the bounds of the intersection of the remaining datasets)". The intersection is what keeps every point of the box inside the range each model was fitted on, so no model is asked to extrapolate. When no surrogate objective is selected at all, the intersection of all four datasets is used. A study that compares subsets against each other should know that they therefore do not share a decision space, and that the comparison is between problems, not between objective counts on one problem. Note: **Three deviations from the paper, and one from the how-to guide, all deliberate.** The paper selects XGBoost for the tensile strength by cross-validation, at a median $R^2$ of 0.8440 against gradient boosting's 0.8437. Gradient boosting is used here instead: the gap is two parts in ten thousand of a quantity whose standard deviation across folds is 0.07, and `xgboost` is not a DESDEO dependency. The paper's Table 3 lists the bounds it used. Five of the seventeen upper bounds computed from the datasets in this repository differ from it -- manganese, nickel, aluminium, boron and copper -- so the data shipped here is not exactly the data the paper's numbers came from. The bounds are computed from the shipped data rather than hard-coded from the table, so that the box always matches the models actually fitted. The paper reports an ideal cost of about 43 USD per kg, which the cost formula above does not reproduce: read as weight per cent times USD per kg, the cheapest point of the box costs well under 1. The paper does not state the unit convention, so the formula is implemented as written and the discrepancy is left visible rather than tuned away. The how-to guide omits the silicon term from the carbon equivalent, uses gradient boosting for the tensile strength, fits every model on all 17 elements, and has neither the Charpy nor the cost objective. This module follows the paper. The training data contains repeated compositions with different measured values -- the same alloy behaves differently after different processing -- so the models cannot interpolate their own training data exactly. The paper's cross-validated $R^2$ is 0.75 for yield strength, 0.84 for tensile strength, 0.67 for elongation and 0.44 for the Charpy energy, which is the one to keep in mind when reading results. Data and models: The datasets ship with the DESDEO repository but not with the installed package. They are looked for in `data_dir`, then in the repository checkout this module lives in, then in the cache; only if none of those has them are they downloaded from GitHub. Trained models are cached under `$XDG_CACHE_HOME/desdeo/MetallApplication` (or `~/.cache/desdeo/MetallApplication`), keyed by the scikit-learn version, the seed, the Charpy temperature and a digest of the training data. Training them takes a few seconds; later calls load the cache. A cached file that fails to load is discarded and retrained rather than raised, which is what happens when scikit-learn is upgraded under an old pickle. `random_state` is passed to every regressor, so the problem is reproducible for a given seed and scikit-learn version. The how-to guide leaves it unset, and its models therefore differ from run to run. Each model is wrapped in a `CompositionModel`, which selects the elements that model was fitted on and, for the Charpy energy, appends the fixed test temperature. The wrapper is what lets every objective share one 17-element decision vector. Args: objectives (tuple[str, ...] | list[str], optional): which objectives to include, as symbols from `OBJECTIVES`. The order given is the order they appear in. Defaults to `MOP_II`. random_state (int, optional): the seed the regressors are fitted with. Defaults to 0. charpy_temperature (float, optional): the temperature in degrees Celsius the Charpy impact energy is evaluated at. Ignored unless `CHARPY` is among the objectives. Defaults to `DEFAULT_CHARPY_TEMPERATURE`. data_dir (Path | None, optional): a directory to look for the datasets in before anywhere else. Defaults to None. cache_dir (Path | None, optional): where to cache datasets and models. Defaults to None, meaning the user cache directory. download (bool, optional): whether the datasets may be fetched from the DESDEO repository when they are not available locally. Defaults to True. Raises: ValueError: if `objectives` is empty, names an unknown objective, or repeats one. FileNotFoundError: if a dataset is missing locally and `download` is False. RuntimeError: if a dataset has to be downloaded and the download fails. Returns: Problem: an instance of the microalloyed steel design problem. """ chosen = list(objectives) if not chosen: raise ValueError("At least one objective is needed; `objectives` was empty.") if unknown := [symbol for symbol in chosen if symbol not in OBJECTIVES]: raise ValueError(f"Unknown objective(s) {unknown}. Available objectives are {sorted(OBJECTIVES)}.") if len(set(chosen)) != len(chosen): raise ValueError(f"`objectives` repeats an objective: {chosen}.") surrogate_targets = [symbol for symbol in chosen if symbol in _SURROGATE_SPEC] # With no surrogate objective there is no data to derive a box from, so all four datasets are used # and the box is the narrowest of the ones any selection could give. bound_targets = surrogate_targets or list(_SURROGATE_SPEC) datasets = { target: _read_dataset(target, data_dir, cache_dir, download=download) for target in dict.fromkeys([*bound_targets, *surrogate_targets]) } lower, upper = _variable_bounds({target: datasets[target] for target in bound_targets}) variables = [ Variable( name=element, symbol=element, variable_type=VariableTypeEnum.real, lowerbound=lower[element], upperbound=upper[element], initial_value=(lower[element] + upper[element]) / 2, ) for element in _ELEMENTS ] analytical = {"CE": _CARBON_EQUIVALENT, "COST": _cost_expression()} problem_objectives = [] for symbol in chosen: description, maximize = OBJECTIVES[symbol] if symbol in analytical: problem_objectives.append( Objective( name=description, symbol=symbol, func=analytical[symbol], objective_type=ObjectiveTypeEnum.analytical, maximize=maximize, is_linear=True, is_convex=True, is_twice_differentiable=True, ) ) continue temperature = charpy_temperature if _SURROGATE_SPEC[symbol].needs_temperature else None problem_objectives.append( Objective( name=description, symbol=symbol, surrogates=[_ensure_surrogate(symbol, datasets[symbol], random_state, temperature, cache_dir)], objective_type=ObjectiveTypeEnum.surrogate, maximize=maximize, is_linear=False, is_convex=False, is_twice_differentiable=False, ) ) charpy_note = f", with the Charpy energy at {charpy_temperature} degrees Celsius" if "CHARPY" in chosen else "" return Problem( name="metallurgical application", description=( f"Microalloyed steel design from 17 alloying elements, with {len(chosen)} objective(s): " f"{', '.join(chosen)}{charpy_note}. The mechanical properties come from surrogate models " "fitted to measurement data; the carbon equivalent and the material cost are analytical." ), variables=variables, objectives=problem_objectives, ) ``` ### momip_ti2 ``` momip_ti2() -> Problem ``` Defines the mixed-integer multiobjective optimization problem test instance 2 (TI2). The problem has four variables, two continuous and two integer. The Pareto optimal solutions hold for solutions with x_1^2 + x_2^2 = 0.25 and (x_3, x_4) = {(0, -1), (-1, 0)}. References Eichfelder, G., Gerlach, T., & Warnow, L. (n.d.). Test Instances for Multiobjective Mixed-Integer Nonlinear Optimization. Source code in `desdeo/problem/testproblems/momip_problem.py` ``` def momip_ti2() -> Problem: """Defines the mixed-integer multiobjective optimization problem test instance 2 (TI2). The problem has four variables, two continuous and two integer. The Pareto optimal solutions hold for solutions with x_1^2 + x_2^2 = 0.25 and (x_3, x_4) = {(0, -1), (-1, 0)}. References: Eichfelder, G., Gerlach, T., & Warnow, L. (n.d.). Test Instances for Multiobjective Mixed-Integer Nonlinear Optimization. """ x_1 = Variable(name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=-1.0, upperbound=1.0) x_2 = Variable(name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=-1.0, upperbound=1.0) x_3 = Variable(name="x_3", symbol="x_3", variable_type=VariableTypeEnum.integer, lowerbound=-1, upperbound=1) x_4 = Variable(name="x_4", symbol="x_4", variable_type=VariableTypeEnum.integer, lowerbound=-1, upperbound=1) f_1 = Objective( name="f_1", symbol="f_1", func="x_1 + x_3", objective_type=ObjectiveTypeEnum.analytical, maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func="x_2 + x_4", objective_type=ObjectiveTypeEnum.analytical, maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_1 = Constraint( name="g_1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func="x_1**2 + x_2**2 - 0.25", is_linear=False, is_convex=False, is_twice_differentiable=True, ) con_2 = Constraint( name="g_2", symbol="g_2", cons_type=ConstraintTypeEnum.LTE, func="x_3**2 + x_4**2 - 1", is_linear=False, is_convex=False, is_twice_differentiable=True, ) return Problem( name="MOMIP Test Instance 2", description="Test instance 2", variables=[x_1, x_2, x_3, x_4], constraints=[con_1, con_2], objectives=[f_1, f_2], ) ``` ### momip_ti7 ``` momip_ti7() -> Problem ``` Defines the mixed-integer multiobjective optimization problem test instance 7 (T7). The problem is defined as follows: [\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = x_1 + x_4 \\ &\\max\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = -(x_2 + x_5) \\ &\\min\_{\\mathbf{x}} & f_3(\\mathbf{x}) & = x_3 + x_6 \\ &\\text{s.t.,} & x_1^2 +x_2^2 + x_3^2 & \\leq 1,\\ & & x_4^2 + x_5^2 + x_6^2 & \\leq 1,\\ & & -1 \\leq x_i \\leq 1&;\\text{for};i={1,2,3},\\ & & x_i \\in {-1, 0, 1}&;\\text{for};i={4, 5, 6}. \\end{align}] In the problem, (x_1, x_2, x_3) are real-valued and (x_4, x_5, x_6) are integer-valued. The problem is convex and differentiable. The Pareto optimal integer assignments are ((x_4, x_5, x_6) \\in {(0,0,-1), (0, -1, 0), (-1,0,0)}), and the real-valued assignments are ({x_1, x_2, x_3 \\in \\mathbb{R}^3 | x_1^2 + x_2^2 + x_3^2 = 1, x_1 \\leq 0, x_2 \\leq 0, x_3 \\leq 0}). Unlike in the original definition, (f_2) is formulated to be maximized instead of minimized. References Eichfelder, G., Gerlach, T., & Warnow, L. (n.d.). Test Instances for Multiobjective Mixed-Integer Nonlinear Optimization. Source code in `desdeo/problem/testproblems/momip_problem.py` ``` def momip_ti7() -> Problem: r"""Defines the mixed-integer multiobjective optimization problem test instance 7 (T7). The problem is defined as follows: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = x_1 + x_4 \\ &\max_{\mathbf{x}} & f_2(\mathbf{x}) & = -(x_2 + x_5) \\ &\min_{\mathbf{x}} & f_3(\mathbf{x}) & = x_3 + x_6 \\ &\text{s.t.,} & x_1^2 +x_2^2 + x_3^2 & \leq 1,\\ & & x_4^2 + x_5^2 + x_6^2 & \leq 1,\\ & & -1 \leq x_i \leq 1&\;\text{for}\;i=\{1,2,3\},\\ & & x_i \in \{-1, 0, 1\}&\;\text{for}\;i=\{4, 5, 6\}. \end{align} In the problem, $x_1, x_2, x_3$ are real-valued and $x_4, x_5, x_6$ are integer-valued. The problem is convex and differentiable. The Pareto optimal integer assignments are $(x_4, x_5, x_6) \in {(0,0,-1), (0, -1, 0), (-1,0,0)}$, and the real-valued assignments are $\{x_1, x_2, x_3 \in \mathbb{R}^3 | x_1^2 + x_2^2 + x_3^2 = 1, x_1 \leq 0, x_2 \leq 0, x_3 \leq 0\}$. Unlike in the original definition, $f_2$ is formulated to be maximized instead of minimized. References: Eichfelder, G., Gerlach, T., & Warnow, L. (n.d.). Test Instances for Multiobjective Mixed-Integer Nonlinear Optimization. """ x_1 = Variable(name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real) x_2 = Variable(name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real) x_3 = Variable(name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real) x_4 = Variable(name="x_4", symbol="x_4", variable_type=VariableTypeEnum.integer, lowerbound=-1, upperbound=1) x_5 = Variable(name="x_5", symbol="x_5", variable_type=VariableTypeEnum.integer, lowerbound=-1, upperbound=1) x_6 = Variable(name="x_6", symbol="x_6", variable_type=VariableTypeEnum.integer, lowerbound=-1, upperbound=1) f_1 = Objective( name="f_1", symbol="f_1", func="x_1 + x_4", objective_type=ObjectiveTypeEnum.analytical, ideal=-3, nadir=3, maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func="-(x_2 + x_5)", objective_type=ObjectiveTypeEnum.analytical, ideal=3, nadir=-3, maximize=True, is_linear=True, is_convex=True, is_twice_differentiable=True, ) f_3 = Objective( name="f_3", symbol="f_3", func="x_3 + x_6", objective_type=ObjectiveTypeEnum.analytical, ideal=-3, nadir=3, maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_1 = Constraint( name="g_1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func="x_1**2 + x_2**2 + x_3**2 - 1", is_linear=False, is_convex=False, is_twice_differentiable=True, ) con_2 = Constraint( name="g_2", symbol="g_2", cons_type=ConstraintTypeEnum.LTE, func="x_4**2 + x_5**2 + x_6**2 - 1", is_linear=False, is_convex=False, is_twice_differentiable=True, ) return Problem( name="MOMIP Test Instance 7", description="Test instance 17", variables=[x_1, x_2, x_3, x_4, x_5, x_6], constraints=[con_1, con_2], objectives=[f_1, f_2, f_3], ) ``` ### multi_valued_constraint_problem ``` multi_valued_constraint_problem() -> Problem ``` Defines a test problem with a multi-valued constraint. The problem has two objectives, two variables, and two constraints, the other of which, is multi-valued. The problem is defined as follows: Returns: | Name | Type | Description | | --------- | --------- | ------------------ | | `Problem` | `Problem` | the problem model. | Source code in `desdeo/problem/testproblems/multi_valued_constraints.py` ``` def multi_valued_constraint_problem() -> Problem: r"""Defines a test problem with a multi-valued constraint. The problem has two objectives, two variables, and two constraints, the other of which, is multi-valued. The problem is defined as follows: \[ \begin{aligned} \text{Min} \quad & f_1(x_1, x_2, y) = x_1^2 + x_2^2 + y^2, \\[4pt] \text{Min} \quad & f_2(x_1, x_2, y) = (x_1 - 2)^2 + (x_2 - 1)^2 + (y - 1)^2, \\[6pt] \text{subject to} \quad & g(x_1, x_2, y) = x_1^2 + x_2 + y - 2 \le 0, \\[4pt] & G(x_1, x_2) = A \begin{bmatrix} x_1 \\[2pt] x_2 \end{bmatrix} \le 0, \quad A = \begin{bmatrix} 1 & -1 \\[2pt] -1 & -2 \end{bmatrix}. \end{aligned} \] Returns: Problem: the problem model. """ xs = TensorVariable( name="x", symbol="X", variable_type=VariableTypeEnum.real, shape=[2, 1], lowerbounds=-5.0, upperbounds=5.0, initial_values=0.1, ) y = Variable( name="y", symbol="y", variable_type=VariableTypeEnum.real, lowerbound=-10.0, upperbound=10.0, initial_value=0.1, ) a = TensorConstant(name="A", symbol="A", shape=[2, 2], values=[[1.0, -1.0], [-1.0, -2.0]]) one = Constant(name="one", symbol="one", value=1.0) f_1_expr = "X[1, 1]**2 + X[2, 1]**2 + y**2" f_2_expr = "(X[1, 1] - 2)**2 + (X[2, 1] - one)**2 + (y - one)**2" g_1_expr = "X[1, 1]**2 + X[2, 1] + y - 2" big_g_expr = "A @ X" f_1 = Objective( name="f1", symbol="f_1", func=f_1_expr, objective_type=ObjectiveTypeEnum.analytical, ideal=0.0, nadir=150.0, is_twice_differentiable=True, ) f_2 = Objective( name="f2", symbol="f_2", func=f_2_expr, ideal=0.0, nadir=206.0, objective_type=ObjectiveTypeEnum.analytical, is_twice_differentiable=True, ) g_1 = Constraint( name="g1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func=g_1_expr, is_twice_differentiable=True ) big_g = Constraint( name="big_g", symbol="G", cons_type=ConstraintTypeEnum.LTE, func=big_g_expr, is_twice_differentiable=True, is_linear=True, is_convex=True, ) return Problem( name="Multi-valued-constraint problem", description="Problem for testing problems with multi-valued constraints.", constants=[a, one], variables=[xs, y], constraints=[g_1, big_g], objectives=[f_1, f_2], ) ``` ### nimbus_test_problem ``` nimbus_test_problem() -> Problem ``` Defines the test problem utilized in the article describing Synchronous NIMBUS. Defines the following multiobjective optimization problem: [\\begin{align} &\\max\_{\\mathbf{x}} & f_1(\\mathbf{x}) &= x_1 x_2\\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) &= (x_1 - 4)^2 + x_2^2\\ &\\min\_{\\mathbf{x}} & f_3(\\mathbf{x}) &= -x_1 - x_2\\ &\\min\_{\\mathbf{x}} & f_4(\\mathbf{x}) &= x_1 - x_2\\ &\\min\_{\\mathbf{x}} & f_5(\\mathbf{x}) &= 50 x_1^4 + 10 x_2^4 \\ &\\min\_{\\mathbf{x}} & f_6(\\mathbf{x}) &= 30 (x_1 - 5)^4 + 100 (x_2 - 3)^4\\ &\\text{s.t.,} && 1 \\leq x_i \\leq 3\\quad i={1,2}, \\end{align}] with the following ideal point (\\mathbf{z}^\\star = \\left[9.0, 2.0, -6.0, -2.0, 60.0, 480.0 \\right]) and nadir point (\\mathbf{z}^\\text{nad} = \\left[ 1.0, 18.0, -2.0, 2.0, 4860.0, 9280.0 \\right]). References Miettinen, K., & Mäkelä, M. M. (2006). Synchronous approach in interactive multiobjective optimization. European Journal of Operational Research, 170(3), 909-922. https://doi.org/10.1016/j.ejor.2004.07.052 Returns: | Name | Type | Description | | --------- | --------- | ------------------------ | | `Problem` | `Problem` | the NIMBUS test problem. | Source code in `desdeo/problem/testproblems/nimbus_problem.py` ``` def nimbus_test_problem() -> Problem: r"""Defines the test problem utilized in the article describing Synchronous NIMBUS. Defines the following multiobjective optimization problem: \begin{align} &\max_{\mathbf{x}} & f_1(\mathbf{x}) &= x_1 x_2\\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) &= (x_1 - 4)^2 + x_2^2\\ &\min_{\mathbf{x}} & f_3(\mathbf{x}) &= -x_1 - x_2\\ &\min_{\mathbf{x}} & f_4(\mathbf{x}) &= x_1 - x_2\\ &\min_{\mathbf{x}} & f_5(\mathbf{x}) &= 50 x_1^4 + 10 x_2^4 \\ &\min_{\mathbf{x}} & f_6(\mathbf{x}) &= 30 (x_1 - 5)^4 + 100 (x_2 - 3)^4\\ &\text{s.t.,} && 1 \leq x_i \leq 3\quad i=\{1,2\}, \end{align} with the following ideal point $\mathbf{z}^\star = \left[9.0, 2.0, -6.0, -2.0, 60.0, 480.0 \right]$ and nadir point $\mathbf{z}^\text{nad} = \left[ 1.0, 18.0, -2.0, 2.0, 4860.0, 9280.0 \right]$. References: Miettinen, K., & Mäkelä, M. M. (2006). Synchronous approach in interactive multiobjective optimization. European Journal of Operational Research, 170(3), 909-922. https://doi.org/10.1016/j.ejor.2004.07.052 Returns: Problem: the NIMBUS test problem. """ variables = [ Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, initial_value=1.0, lowerbound=1.0, upperbound=3.0, ), Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, initial_value=1.0, lowerbound=1.0, upperbound=3.0, ), ] f_1_expr = "x_1 * x_2" f_2_expr = "(x_1 - 4)**2 + x_2**2" f_3_expr = "-x_1 - x_2" f_4_expr = "x_1 - x_2" f_5_expr = "50 * x_1**4 + 10 * x_2**4" f_6_expr = "30 * (x_1 - 5)**4 + 100*(x_2 - 3)**4" objectives = [ Objective( name="Objective 1", symbol="f_1", func=f_1_expr, maximize=True, objective_type=ObjectiveTypeEnum.analytical, ideal=9.0, nadir=1.0, is_convex=False, is_linear=False, is_twice_differentiable=True, ), Objective( name="Objective 2", symbol="f_2", func=f_2_expr, maximize=False, objective_type=ObjectiveTypeEnum.analytical, ideal=2.0, nadir=18.0, is_convex=False, is_linear=False, is_twice_differentiable=True, ), Objective( name="Objective 3", symbol="f_3", func=f_3_expr, maximize=False, objective_type=ObjectiveTypeEnum.analytical, ideal=-6.0, nadir=-2.0, is_convex=True, is_linear=True, is_twice_differentiable=True, ), Objective( name="Objective 4", symbol="f_4", func=f_4_expr, maximize=False, objective_type=ObjectiveTypeEnum.analytical, ideal=-2.0, nadir=2.0, is_convex=True, is_linear=True, is_twice_differentiable=True, ), Objective( name="Objective 5", symbol="f_5", func=f_5_expr, maximize=False, objective_type=ObjectiveTypeEnum.analytical, ideal=60.0, nadir=4860.0, is_convex=False, is_linear=False, is_twice_differentiable=True, ), Objective( name="Objective 6", symbol="f_6", func=f_6_expr, maximize=False, objective_type=ObjectiveTypeEnum.analytical, ideal=480.0, nadir=9280.0, is_convex=False, is_linear=False, is_twice_differentiable=True, ), ] return Problem( name="NIMBUS test problem", description="The test problem used in the Synchronous NIMBUS article", variables=variables, objectives=objectives, ) ``` ### pareto_navigator_test_problem ``` pareto_navigator_test_problem() -> Problem ``` Defines the problem utilized in the (convex) Pareto navigator article. The problem is defined as follows: [\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = -x_1 - x_2 + 5 \\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = 0.2(x_1^2 -10x_1 + x_2^2 - 4x_2 + 11) \\ &\\min\_{\\mathbf{x}} & f_3(\\mathbf{x}) & = (5 - x_1)(x_2 - 11)\\ &\\text{s.t.,} & 3x_1 + x_2 - 12 & \\leq 0,\\ & & 2x_1 + x_2 - 9 & \\leq 0,\\ & & x_1 + 2x_2 - 12 & \\leq 0,\\ & & 0 \\leq x_1 & \\leq 4,\\ & & 0 \\leq x_2 & \\leq 6. \\end{align}] The problem comes with seven pre-defined Pareto optimal solutions that were utilized in the original article as well. From these, the ideal and nadir points of the problem are approximated also. References Eskelinen, P., Miettinen, K., Klamroth, K., & Hakanen, J. (2010). Pareto navigator for interactive nonlinear multiobjective optimization. OR Spectrum, 32(1), 211-227. Source code in `desdeo/problem/testproblems/pareto_navigator_problem.py` ``` def pareto_navigator_test_problem() -> Problem: r"""Defines the problem utilized in the (convex) Pareto navigator article. The problem is defined as follows: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = -x_1 - x_2 + 5 \\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) & = 0.2(x_1^2 -10x_1 + x_2^2 - 4x_2 + 11) \\ &\min_{\mathbf{x}} & f_3(\mathbf{x}) & = (5 - x_1)(x_2 - 11)\\ &\text{s.t.,} & 3x_1 + x_2 - 12 & \leq 0,\\ & & 2x_1 + x_2 - 9 & \leq 0,\\ & & x_1 + 2x_2 - 12 & \leq 0,\\ & & 0 \leq x_1 & \leq 4,\\ & & 0 \leq x_2 & \leq 6. \end{align} The problem comes with seven pre-defined Pareto optimal solutions that were utilized in the original article as well. From these, the ideal and nadir points of the problem are approximated also. References: Eskelinen, P., Miettinen, K., Klamroth, K., & Hakanen, J. (2010). Pareto navigator for interactive nonlinear multiobjective optimization. OR Spectrum, 32(1), 211-227. """ x_1 = Variable(name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=4) x_2 = Variable(name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=6) f_1 = Objective( name="f_1", symbol="f_1", func="-x_1 - x_2 + 5", objective_type=ObjectiveTypeEnum.analytical, ideal=-2.0, nadir=5.0, maximize=False, ) f_2 = Objective( name="f_2", symbol="f_2", func="0.2*(x_1**2 - 10*x_1 + x_2**2 - 4*x_2 + 11)", objective_type=ObjectiveTypeEnum.analytical, ideal=-3.1, nadir=4.60, maximize=False, ) f_3 = Objective( name="f_3", symbol="f_3", func="(5 - x_1) * (x_2 - 11)", objective_type=ObjectiveTypeEnum.analytical, ideal=-55.0, nadir=-14.25, maximize=False, ) con_1 = Constraint(name="g_1", symbol="g_1", func="3*x_1 + x_2 - 12", cons_type=ConstraintTypeEnum.LTE) con_2 = Constraint(name="g_2", symbol="g_2", func="2*x_1 + x_2 - 9", cons_type=ConstraintTypeEnum.LTE) con_3 = Constraint(name="g_3", symbol="g_3", func="x_1 + 2*x_2 - 12", cons_type=ConstraintTypeEnum.LTE) representation = DiscreteRepresentation( variable_values={"x_1": [0, 0, 0, 0, 0, 0, 0], "x_2": [0, 0, 0, 0, 0, 0, 0]}, objective_values={ "f_1": [-2.0, -1.0, 0.0, 1.38, 1.73, 2.48, 5.0], "f_2": [0.0, 4.6, -3.1, 0.62, 1.72, 1.45, 2.2], "f_3": [-18.0, -25.0, -14.25, -35.33, -38.64, -42.41, -55.0], }, non_dominated=True, ) return Problem( name="The (convex) Pareto navigator problem.", description="The test problem used in the (convex) Pareto navigator paper.", variables=[x_1, x_2], objectives=[f_1, f_2, f_3], constraints=[con_1, con_2, con_3], discrete_representation=representation, ) ``` ### re21 ``` re21( f: float = 10.0, sigma: float = 10.0, e: float = 2.0 * 100000.0, l: float = 200.0, ) -> Problem ``` Defines the four bar truss design problem. The objective functions and constraints for the four bar truss design problem are defined as follows: \[\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = L(2x_1 + \\sqrt{2}x_2 + \\sqrt{x_3} + x_4) \\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = \\frac{FL}{E}\\left(\\frac{2}{x_1} + \\frac{2\\sqrt{2}}{x_2} - \\frac{2\\sqrt{2}}{x_3} + \\frac{2}{x_4}\\right) \\ \\end{align}\] where (x_1, x_4 \\in [a, 3a]), (x_2, x_3 \\in [\\sqrt{2}a, 3a]), and (a = F/\\sigma). The parameters are defined as (F = 10) (kN), (E = 2e^5) (kN/cm^2), (L = 200) (cm), and (\\sigma = 10) (kN/cm^2). References Cheng, F. Y., & Li, X. S. (1999). Generalized center method for multiobjective engineering optimization. Engineering Optimization, 31(5), 641-661. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. https://github.com/ryojitanabe/reproblems/blob/master/reproblem_python_ver/reproblem.py Parameters: | Name | Type | Description | Default | | ------- | ---------- | ------------------------------------------------ | ---------------- | | `f` | `float` | Force (kN). Defaults to 10.0. | `10.0` | | `sigma` | `optional` | Stress (kN/cm^2). Defaults to 10.0. | `10.0` | | `e` | `float` | Young modulus? (kN/cm^2). Defaults to 2.0 * 1e5. | `2.0 * 100000.0` | | `l` | `float` | Length (cm). Defaults to 200.0. | `200.0` | Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------- | | `Problem` | `Problem` | an instance of the four bar truss design problem. | Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re21(f: float = 10.0, sigma: float = 10.0, e: float = 2.0 * 1e5, l: float = 200.0) -> Problem: r"""Defines the four bar truss design problem. The objective functions and constraints for the four bar truss design problem are defined as follows: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = L(2x_1 + \sqrt{2}x_2 + \sqrt{x_3} + x_4) \\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) & = \frac{FL}{E}\left(\frac{2}{x_1} + \frac{2\sqrt{2}}{x_2} - \frac{2\sqrt{2}}{x_3} + \frac{2}{x_4}\right) \\ \end{align} where $x_1, x_4 \in [a, 3a]$, $x_2, x_3 \in [\sqrt{2}a, 3a]$, and $a = F/\sigma$. The parameters are defined as $F = 10$ $kN$, $E = 2e^5$ $kN/cm^2$, $L = 200$ $cm$, and $\sigma = 10$ $kN/cm^2$. References: Cheng, F. Y., & Li, X. S. (1999). Generalized center method for multiobjective engineering optimization. Engineering Optimization, 31(5), 641-661. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. https://github.com/ryojitanabe/reproblems/blob/master/reproblem_python_ver/reproblem.py Args: f (float, optional): Force (kN). Defaults to 10.0. sigma (float. optional): Stress (kN/cm^2). Defaults to 10.0. e (float, optional): Young modulus? (kN/cm^2). Defaults to 2.0 * 1e5. l (float, optional): Length (cm). Defaults to 200.0. Returns: Problem: an instance of the four bar truss design problem. """ a = f / sigma x_1 = Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=a, upperbound=3 * a, initial_value=2 * a, ) x_2 = Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=np.sqrt(2.0) * a, upperbound=3 * a, initial_value=2 * a, ) x_3 = Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=np.sqrt(2.0) * a, upperbound=3 * a, initial_value=2 * a, ) x_4 = Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=a, upperbound=3 * a, initial_value=2 * a, ) f_1 = Objective( name="f_1", symbol="f_1", func=f"{l} * ((2 * x_1) + {np.sqrt(2.0)} * x_2 + Sqrt(x_3) + x_4)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func=f"({(f * l) / e} * ((2.0 / x_1) + (2.0 * {np.sqrt(2.0)} / x_2) - " f"(2.0 * {np.sqrt(2.0)} / x_3) + (2.0 / x_4)))", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) return Problem( name="RE21", description="the four bar truss design problem", variables=[x_1, x_2, x_3, x_4], objectives=[f_1, f_2], ) ``` ### re22 ``` re22() -> Problem ``` The reinforced concrete beam design problem. The objective functions and constraints for the reinforced concrete beam design problem are defined as follows: [\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = 29.4x_1 + 0.6x_2x_3 \\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = \\sum\_{i=1}^2 \\max{g_i(\\mathbf{x}), 0} \\ &\\text{s.t.,} & g_1(\\mathbf{x}) & = x_1x_3 - 7.735\\frac{x_1^2}{x_2} - 180 \\geq 0,\\ & & g_2(\\mathbf{x}) & = 4 - \\frac{x_3}{x_2} \\geq 0. \\end{align}] where (x_2 \\in [0, 20]) and (x_3 \\in [0, 40]). References Amir, H. M., & Hasegawa, T. (1989). Nonlinear mixed-discrete structural optimization. Journal of Structural Engineering, 115(3), 626-646. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. https://github.com/ryojitanabe/reproblems/blob/master/reproblem_python_ver/reproblem.py Returns: | Name | Type | Description | | --------- | --------- | ----------------------------------------------------------- | | `Problem` | `Problem` | an instance of the reinforced concrete beam design problem. | Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re22() -> Problem: r"""The reinforced concrete beam design problem. The objective functions and constraints for the reinforced concrete beam design problem are defined as follows: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = 29.4x_1 + 0.6x_2x_3 \\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) & = \sum_{i=1}^2 \max\{g_i(\mathbf{x}), 0\} \\ &\text{s.t.,} & g_1(\mathbf{x}) & = x_1x_3 - 7.735\frac{x_1^2}{x_2} - 180 \geq 0,\\ & & g_2(\mathbf{x}) & = 4 - \frac{x_3}{x_2} \geq 0. \end{align} where $x_2 \in [0, 20]$ and $x_3 \in [0, 40]$. References: Amir, H. M., & Hasegawa, T. (1989). Nonlinear mixed-discrete structural optimization. Journal of Structural Engineering, 115(3), 626-646. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. https://github.com/ryojitanabe/reproblems/blob/master/reproblem_python_ver/reproblem.py Returns: Problem: an instance of the reinforced concrete beam design problem. """ x_2 = Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=20, initial_value=10 ) x_3 = Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=40, initial_value=20 ) # x_1 pre-defined discrete values feasible_values = np.array( [ 0.20, 0.31, 0.40, 0.44, 0.60, 0.62, 0.79, 0.80, 0.88, 0.93, 1.0, 1.20, 1.24, 1.32, 1.40, 1.55, 1.58, 1.60, 1.76, 1.80, 1.86, 2.0, 2.17, 2.20, 2.37, 2.40, 2.48, 2.60, 2.64, 2.79, 2.80, 3.0, 3.08, 3.10, 3.16, 3.41, 3.52, 3.60, 3.72, 3.95, 3.96, 4.0, 4.03, 4.20, 4.34, 4.40, 4.65, 4.74, 4.80, 4.84, 5.0, 5.28, 5.40, 5.53, 5.72, 6.0, 6.16, 6.32, 6.60, 7.11, 7.20, 7.80, 7.90, 8.0, 8.40, 8.69, 9.0, 9.48, 10.27, 11.0, 11.06, 11.85, 12.0, 13.0, 14.0, 15.0, ] ) variables = [x_2, x_3] # forming a set of variables and a constraint to make sure x_1 is from the set of feasible values x_1_eprs = [] for i in range(len(feasible_values)): x = Variable( name=f"x_1_{i}", symbol=f"x_1_{i}", variable_type=VariableTypeEnum.binary, lowerbound=0, upperbound=1 ) variables.append(x) expr = f"x_1_{i} * {feasible_values[i]}" x_1_eprs.append(expr) x_1_eprs = " + ".join(x_1_eprs) sum_expr = [f"x_1_{i}" for i in range(len(feasible_values))] sum_expr = " + ".join(sum_expr) + " - 1" x_1_con = Constraint( name="x_1_con", symbol="x_1_con", cons_type=ConstraintTypeEnum.EQ, func=sum_expr, is_linear=True ) g_1 = Constraint( name="g_1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func=f"- (({x_1_eprs}) * x_3 - 7.735 * (({x_1_eprs})**2 / x_2) - 180)", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) g_2 = Constraint( name="g_2", symbol="g_2", cons_type=ConstraintTypeEnum.LTE, func="-(4 - x_3 / x_2)", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_1 = Objective( name="f_1", symbol="f_1", func=f"29.4 * ({x_1_eprs}) + 0.6 * x_2 * x_3", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func=f"Max(({x_1_eprs}) * x_3 - 7.735 * (({x_1_eprs})**2 / x_2) - 180, 0) + Max(4 - x_3 / x_2, 0)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) return Problem( name="re22", description="The reinforced concrete beam design problem", variables=variables, objectives=[f_1, f_2], constraints=[g_1, g_2, x_1_con], ) ``` ### re23 ``` re23() -> Problem ``` The pressure vessel design problem. The objective functions and constraints for the pressure vessel design problem are defined as follows: [\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = 0.6224x_1x_3x_4 + 1.7781x_2x_3^2 + 3.1661x_1^2x_4 + 19.84x_1^2x_3 \\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = \\sum\_{i=1}^3 \\max{g_i(\\mathbf{x}), 0} \\ &\\text{s.t.,} & g_1(\\mathbf{x}) & = -x_1 + 0.0193x_3 \\leq 0,\\ & & g_2(\\mathbf{x}) & = -x_2 + 0.00954x_3 \\leq 0, \\ & & g_3(\\mathbf{x}) & = -\\pi x_3^2x_4 - \\frac{4}{3}\\pi x_3^3 + 1,296,000 \\leq 0. \\end{align}] ``` where $x_1, x_2 \in \{1,\dots,100\}$, $x_3 \in [10, 200]$, and $x_4 \in [10, 240]$. $x_1$ and $x_2$ are integer multiples of 0.0625. $x_1$, $x_2$, $x_3$, and $x_4$ represent the thicknesses of the shell, the head of a pressure vessel, the inner radius, and the length of the cylindrical section, respectively. We determined the ranges of $x_2$ and $x_3$ according to [S.3]. ``` References Kannan, B. K., & Kramer, S. N. (1994). An augmented Lagrange multiplier based method for mixed integer discrete continuous optimization and its applications to mechanical design. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. https://github.com/ryojitanabe/reproblems/blob/master/reproblem_python_ver/reproblem.py Returns: | Name | Type | Description | | --------- | --------- | -------------------------------------------------- | | `Problem` | `Problem` | an instance of the pressure vessel design problem. | Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re23() -> Problem: r"""The pressure vessel design problem. The objective functions and constraints for the pressure vessel design problem are defined as follows: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = 0.6224x_1x_3x_4 + 1.7781x_2x_3^2 + 3.1661x_1^2x_4 + 19.84x_1^2x_3 \\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) & = \sum_{i=1}^3 \max\{g_i(\mathbf{x}), 0\} \\ &\text{s.t.,} & g_1(\mathbf{x}) & = -x_1 + 0.0193x_3 \leq 0,\\ & & g_2(\mathbf{x}) & = -x_2 + 0.00954x_3 \leq 0, \\ & & g_3(\mathbf{x}) & = -\pi x_3^2x_4 - \frac{4}{3}\pi x_3^3 + 1\,296\,000 \leq 0. \end{align} where $x_1, x_2 \in \{1,\dots,100\}$, $x_3 \in [10, 200]$, and $x_4 \in [10, 240]$. $x_1$ and $x_2$ are integer multiples of 0.0625. $x_1$, $x_2$, $x_3$, and $x_4$ represent the thicknesses of the shell, the head of a pressure vessel, the inner radius, and the length of the cylindrical section, respectively. We determined the ranges of $x_2$ and $x_3$ according to [S.3]. References: Kannan, B. K., & Kramer, S. N. (1994). An augmented Lagrange multiplier based method for mixed integer discrete continuous optimization and its applications to mechanical design. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. https://github.com/ryojitanabe/reproblems/blob/master/reproblem_python_ver/reproblem.py Returns: Problem: an instance of the pressure vessel design problem. """ x_1 = Variable(name="x_1", symbol="x_1", variable_type=VariableTypeEnum.integer, lowerbound=1, upperbound=100) x_2 = Variable(name="x_2", symbol="x_2", variable_type=VariableTypeEnum.integer, lowerbound=1, upperbound=100) x_3 = Variable(name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=10, upperbound=200) x_4 = Variable(name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=10, upperbound=240) # variables x_1 and x_2 are integer multiples of 0.0625 x_1_exprs = "(0.0625 * x_1)" x_2_exprs = "(0.0625 * x_2)" g_1 = Constraint( name="g_1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func=f"-({x_1_exprs} - 0.0193 * x_3)", is_linear=True, is_convex=False, # Not checked is_twice_differentiable=True, ) g_2 = Constraint( name="g_2", symbol="g_2", cons_type=ConstraintTypeEnum.LTE, func=f"-({x_2_exprs} - 0.00954 * x_3)", is_linear=True, is_convex=False, # Not checked is_twice_differentiable=True, ) g_3 = Constraint( name="g_3", symbol="g_3", cons_type=ConstraintTypeEnum.LTE, func=f"-({np.pi} * x_3**2 * x_4 + (4/3) * {np.pi} * x_3**3 - 1296000)", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_1 = Objective( name="f_1", symbol="f_1", func=f"0.6224 * {x_1_exprs} * x_3 * x_4 + (1.7781 * {x_2_exprs} * x_3**2) + " f"(3.1661 * {x_1_exprs}**2 * x_4) + (19.84 * {x_1_exprs}**2 * x_3)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func=f"Max({x_1_exprs} - 0.0193 * x_3, 0) + Max({x_2_exprs} - 0.00954 * x_3, 0) + " f"Max({np.pi} * x_3**2 * x_4 + (4/3) * {np.pi} * x_3**3 - 1296000, 0)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) return Problem( name="re23", description="The pressure vessel design problem", variables=[x_1, x_2, x_3, x_4], objectives=[f_1, f_2], constraints=[g_1, g_2, g_3], ) ``` ### re24 ``` re24() -> Problem ``` The hatch cover design problem. The objective functions and constraints for the hatch cover design problem are defined as follows: [\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = x_1 + 120x_2 \\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = \\sum\_{i=1}^4 \\max{g_i(\\mathbf{x}), 0} \\ &\\text{s.t.,} & g_1(\\mathbf{x}) & = 1.0 - \\frac{\\sigma_b}{\\sigma\_{b,max}} \\geq 0,\\ & & g_2(\\mathbf{x}) & = 1.0 - \\frac{\\tau}{\\tau\_{max}} \\geq 0, \\ & & g_3(\\mathbf{x}) & = 1.0 - \\frac{\\delta}{\\delta\_{max}} \\geq 0, \\ & & g_4(\\mathbf{x}) & = 1.0 - \\frac{\\sigma_b}{\\sigma\_{k}} \\geq 0, \\end{align}] where (x_1 \\in [0.5, 4]) and (x_2 \\in [4, 50]). The parameters are defined as (\\sigma\_{b,max} = 700 kg/cm^2), (\\tau\_{max} = 450 kg/cm), (\\delta\_{max} = 1.5 cm), (\\sigma_k = Ex_1^2/100 kg/cm^2), (\\sigma_b = 4500/(x_1x_2) kg/cm^2), (\\tau = 1800/x_2 kg/cm^2), (\\delta = 56.2 \\times 10^4/(Ex_1x_2^2)), and (E = 700,000 kg/cm^2). References Amir, H. M., & Hasegawa, T. (1989). Nonlinear mixed-discrete structural optimization. Journal of Structural Engineering, 115(3), 626-646. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. https://github.com/ryojitanabe/reproblems/blob/master/reproblem_python_ver/reproblem.py Returns: | Name | Type | Description | | --------- | --------- | ---------------------------------------------- | | `Problem` | `Problem` | an instance of the hatch cover design problem. | Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re24() -> Problem: r"""The hatch cover design problem. The objective functions and constraints for the hatch cover design problem are defined as follows: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = x_1 + 120x_2 \\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) & = \sum_{i=1}^4 \max\{g_i(\mathbf{x}), 0\} \\ &\text{s.t.,} & g_1(\mathbf{x}) & = 1.0 - \frac{\sigma_b}{\sigma_{b,max}} \geq 0,\\ & & g_2(\mathbf{x}) & = 1.0 - \frac{\tau}{\tau_{max}} \geq 0, \\ & & g_3(\mathbf{x}) & = 1.0 - \frac{\delta}{\delta_{max}} \geq 0, \\ & & g_4(\mathbf{x}) & = 1.0 - \frac{\sigma_b}{\sigma_{k}} \geq 0, \end{align} where $x_1 \in [0.5, 4]$ and $x_2 \in [4, 50]$. The parameters are defined as $\sigma_{b,max} = 700 kg/cm^2$, $\tau_{max} = 450 kg/cm$, $\delta_{max} = 1.5 cm$, $\sigma_k = Ex_1^2/100 kg/cm^2$, $\sigma_b = 4500/(x_1x_2) kg/cm^2$, $\tau = 1800/x_2 kg/cm^2$, $\delta = 56.2 \times 10^4/(Ex_1x_2^2)$, and $E = 700\,000 kg/cm^2$. References: Amir, H. M., & Hasegawa, T. (1989). Nonlinear mixed-discrete structural optimization. Journal of Structural Engineering, 115(3), 626-646. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. https://github.com/ryojitanabe/reproblems/blob/master/reproblem_python_ver/reproblem.py Returns: Problem: an instance of the hatch cover design problem. """ x_1 = Variable(name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.5, upperbound=4) x_2 = Variable(name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=4, upperbound=50) sigma_b = "(4500 / (x_1 * x_2))" sigma_k = "((700000 * x_1**2) / 100)" tau = "(1800 / x_2)" delta = "(56.2 * 10**4 / (700000 * x_1 * x_2**2))" g_1 = Constraint( name="g_1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func=f"-(1 - {sigma_b} / 700)", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) g_2 = Constraint( name="g_2", symbol="g_2", cons_type=ConstraintTypeEnum.LTE, func=f"-(1 - {tau} / 450)", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) g_3 = Constraint( name="g_3", symbol="g_3", cons_type=ConstraintTypeEnum.LTE, func=f"-(1 - {delta} / 1.5)", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) g_4 = Constraint( name="g_4", symbol="g_4", cons_type=ConstraintTypeEnum.LTE, func=f"-(1 - {sigma_b} / {sigma_k})", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_1 = Objective( name="f_1", symbol="f_1", func="x_1 + 120 * x_2", objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=False, # Not checked is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func=f"Max(-(1 - {sigma_b} / 700), 0) + Max(-(1 - {tau} / 450), 0) + " f"Max(-(1 - {delta} / 1.5), 0) + Max(-(1 - {sigma_b} / {sigma_k}), 0)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) return Problem( name="re24", description="The hatch cover design problem", variables=[x_1, x_2], objectives=[f_1, f_2], constraints=[g_1, g_2, g_3, g_4], ) ``` ### re31 ``` re31() -> Problem ``` The two bar truss design problem. Two bars carry a load between two fixed points. The first two objectives are the structural weight and the resultant displacement of the joint; the third is the sum of the three constraint violations, which is how the RE suite turns the original constrained problem into a bound-constrained one: [\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = x_1\\sqrt{16 + x_3^2} + x_2\\sqrt{1 + x_3^2} \\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = \\frac{20\\sqrt{16 + x_3^2}}{x_3 x_1} \\ &\\min\_{\\mathbf{x}} & f_3(\\mathbf{x}) & = \\sum\_{i=1}^3 \\max{-g_i(\\mathbf{x}), 0} \\ &\\text{where} & g_1(\\mathbf{x}) & = 0.1 - f_1(\\mathbf{x}) \\geq 0,\\ & & g_2(\\mathbf{x}) & = 10^5 - f_2(\\mathbf{x}) \\geq 0, \\ & & g_3(\\mathbf{x}) & = 10^5 - \\frac{80\\sqrt{1 + x_3^2}}{x_3 x_2} \\geq 0, \\end{align}] where (x_1, x_2 \\in [10^{-5}, 100]) and (x_3 \\in [1, 3]). (x_1) and (x_2) are the lengths of the two bars and (x_3) is the vertical distance from the second bar. The original problem leaves (x_1) and (x_2) unbounded above; the RE suite adds bounds to make the problem bound-constrained. Note Following the RE suite, the returned problem has **no constraints** — the constraint violations are folded into `f_3`. The constrained variant is CRE31, which is not implemented here. References Coello Coello, C. A., & Pulido, G. T. (2005). Multiobjective structural optimization using a microgenetic algorithm. Structural and Multidisciplinary Optimization, 30(5), 388-403. https://doi.org/10.1007/s00158-005-0527-z. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------ | | `Problem` | `Problem` | an instance of the two bar truss design problem. | Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re31() -> Problem: r"""The two bar truss design problem. Two bars carry a load between two fixed points. The first two objectives are the structural weight and the resultant displacement of the joint; the third is the sum of the three constraint violations, which is how the RE suite turns the original constrained problem into a bound-constrained one: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = x_1\sqrt{16 + x_3^2} + x_2\sqrt{1 + x_3^2} \\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) & = \frac{20\sqrt{16 + x_3^2}}{x_3 x_1} \\ &\min_{\mathbf{x}} & f_3(\mathbf{x}) & = \sum_{i=1}^3 \max\{-g_i(\mathbf{x}), 0\} \\ &\text{where} & g_1(\mathbf{x}) & = 0.1 - f_1(\mathbf{x}) \geq 0,\\ & & g_2(\mathbf{x}) & = 10^5 - f_2(\mathbf{x}) \geq 0, \\ & & g_3(\mathbf{x}) & = 10^5 - \frac{80\sqrt{1 + x_3^2}}{x_3 x_2} \geq 0, \end{align} where $x_1, x_2 \in [10^{-5}, 100]$ and $x_3 \in [1, 3]$. $x_1$ and $x_2$ are the lengths of the two bars and $x_3$ is the vertical distance from the second bar. The original problem leaves $x_1$ and $x_2$ unbounded above; the RE suite adds bounds to make the problem bound-constrained. Note: Following the RE suite, the returned problem has **no constraints** — the constraint violations are folded into `f_3`. The constrained variant is CRE31, which is not implemented here. References: Coello Coello, C. A., & Pulido, G. T. (2005). Multiobjective structural optimization using a microgenetic algorithm. Structural and Multidisciplinary Optimization, 30(5), 388-403. https://doi.org/10.1007/s00158-005-0527-z. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. Returns: Problem: an instance of the two bar truss design problem. """ x_1 = Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=1e-5, upperbound=100, initial_value=50 ) x_2 = Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=1e-5, upperbound=100, initial_value=50 ) x_3 = Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=1, upperbound=3, initial_value=2 ) f_1_expr = "x_1 * Sqrt(16 + x_3**2) + x_2 * Sqrt(1 + x_3**2)" f_2_expr = "(20 * Sqrt(16 + x_3**2)) / (x_3 * x_1)" # The g_i are written in the paper's ">= 0" orientation, so a negative value is a violation. extras = [ ExtraFunction( name="g_1", symbol="g_1", func=f"0.1 - ({f_1_expr})", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ), ExtraFunction( name="g_2", symbol="g_2", func=f"100000 - ({f_2_expr})", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ), ExtraFunction( name="g_3", symbol="g_3", func="100000 - (80 * Sqrt(1 + x_3**2)) / (x_3 * x_2)", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ), ] f_1 = Objective( name="f_1", symbol="f_1", func=f_1_expr, objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func=f_2_expr, objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_3 = Objective( name="f_3", symbol="f_3", func=_violation_objective(["g_1", "g_2", "g_3"]), objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) return Problem( name="re31", description="The two bar truss design problem", variables=[x_1, x_2, x_3], objectives=[f_1, f_2, f_3], extra_funcs=extras, ) ``` ### re32 ``` re32( p: float = 6000.0, l: float = 14.0, e: float = 30.0 * 1000000.0, g: float = 12.0 * 1000000.0, tau_max: float = 13600.0, sigma_max: float = 30000.0, ) -> Problem ``` The welded beam design problem. A beam is welded to a rigid support and carries a load at its free end. The first two objectives are the fabrication cost and the end deflection; the third is the sum of the four constraint violations: [\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = 1.10471x_1^2x_2 + 0.04811x_3x_4(14 + x_2) \\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = \\frac{4PL^3}{Ex_4x_3^3} \\ &\\min\_{\\mathbf{x}} & f_3(\\mathbf{x}) & = \\sum\_{i=1}^4 \\max{-g_i(\\mathbf{x}), 0} \\ &\\text{where} & g_1(\\mathbf{x}) & = \\tau\_{max} - \\tau(\\mathbf{x}) \\geq 0,\\ & & g_2(\\mathbf{x}) & = \\sigma\_{max} - \\sigma(\\mathbf{x}) \\geq 0, \\ & & g_3(\\mathbf{x}) & = x_4 - x_1 \\geq 0, \\ & & g_4(\\mathbf{x}) & = P_C(\\mathbf{x}) - P \\geq 0, \\end{align}] with the stress terms [\\begin{align} \\tau(\\mathbf{x}) & = \\sqrt{(\\tau')^2 + \\frac{2\\tau'\\tau''x_2}{2R} + (\\tau'')^2}, & \\tau' & = \\frac{P}{\\sqrt{2}x_1x_2}, & \\tau'' & = \\frac{MR}{J}, \\ M & = P\\left(L + \\frac{x_2}{2}\\right), & R & = \\sqrt{\\frac{x_2^2}{4} + \\left(\\frac{x_1 + x_3}{2}\\right)^2}, & J & = 2\\left(\\sqrt{2}x_1x_2\\left(\\frac{x_2^2}{12} + \\left(\\frac{x_1 + x_3}{2}\\right)^2\\right)\\right), \\ \\sigma(\\mathbf{x}) & = \\frac{6PL}{x_4x_3^2}, & P_C(\\mathbf{x}) & = \\frac{4.013E\\sqrt{x_3^2x_4^6/36}}{L^2} \\left(1 - \\frac{x_3}{2L}\\sqrt{\\frac{E}{4G}}\\right). & \\end{align}] where (x_1, x_4 \\in [0.125, 5]) and (x_2, x_3 \\in [0.1, 10]). The four variables adjust the size of the beam: the weld thickness, the weld length, the beam depth and the beam width. Note Following the RE suite, the returned problem has **no constraints** — the constraint violations are folded into `f_3`. The constrained variant is CRE32, which is not implemented here. References Ray, T., & Liew, K. M. (2002). A swarm metaphor for multiobjective design optimization. Engineering Optimization, 34(2), 141-153. https://doi.org/10.1080/03052150210915. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. Parameters: | Name | Type | Description | Default | | ----------- | ------- | --------------------------------------------------------------- | ------------------ | | `p` | `float` | the load on the beam (lb). Defaults to 6000.0. | `6000.0` | | `l` | `float` | the beam overhang length (in). Defaults to 14.0. | `14.0` | | `e` | `float` | Young's modulus (psi). Defaults to 30.0e6. | `30.0 * 1000000.0` | | `g` | `float` | the shear modulus (psi). Defaults to 12.0e6. | `12.0 * 1000000.0` | | `tau_max` | `float` | the maximum allowable shear stress (psi). Defaults to 13600.0. | `13600.0` | | `sigma_max` | `float` | the maximum allowable normal stress (psi). Defaults to 30000.0. | `30000.0` | Returns: | Name | Type | Description | | --------- | --------- | ---------------------------------------------- | | `Problem` | `Problem` | an instance of the welded beam design problem. | Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re32( p: float = 6000.0, l: float = 14.0, e: float = 30.0 * 1e6, g: float = 12.0 * 1e6, tau_max: float = 13600.0, sigma_max: float = 30000.0, ) -> Problem: r"""The welded beam design problem. A beam is welded to a rigid support and carries a load at its free end. The first two objectives are the fabrication cost and the end deflection; the third is the sum of the four constraint violations: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = 1.10471x_1^2x_2 + 0.04811x_3x_4(14 + x_2) \\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) & = \frac{4PL^3}{Ex_4x_3^3} \\ &\min_{\mathbf{x}} & f_3(\mathbf{x}) & = \sum_{i=1}^4 \max\{-g_i(\mathbf{x}), 0\} \\ &\text{where} & g_1(\mathbf{x}) & = \tau_{max} - \tau(\mathbf{x}) \geq 0,\\ & & g_2(\mathbf{x}) & = \sigma_{max} - \sigma(\mathbf{x}) \geq 0, \\ & & g_3(\mathbf{x}) & = x_4 - x_1 \geq 0, \\ & & g_4(\mathbf{x}) & = P_C(\mathbf{x}) - P \geq 0, \end{align} with the stress terms \begin{align} \tau(\mathbf{x}) & = \sqrt{(\tau')^2 + \frac{2\tau'\tau''x_2}{2R} + (\tau'')^2}, & \tau' & = \frac{P}{\sqrt{2}x_1x_2}, & \tau'' & = \frac{MR}{J}, \\ M & = P\left(L + \frac{x_2}{2}\right), & R & = \sqrt{\frac{x_2^2}{4} + \left(\frac{x_1 + x_3}{2}\right)^2}, & J & = 2\left(\sqrt{2}x_1x_2\left(\frac{x_2^2}{12} + \left(\frac{x_1 + x_3}{2}\right)^2\right)\right), \\ \sigma(\mathbf{x}) & = \frac{6PL}{x_4x_3^2}, & P_C(\mathbf{x}) & = \frac{4.013E\sqrt{x_3^2x_4^6/36}}{L^2} \left(1 - \frac{x_3}{2L}\sqrt{\frac{E}{4G}}\right). & \end{align} where $x_1, x_4 \in [0.125, 5]$ and $x_2, x_3 \in [0.1, 10]$. The four variables adjust the size of the beam: the weld thickness, the weld length, the beam depth and the beam width. Note: Following the RE suite, the returned problem has **no constraints** — the constraint violations are folded into `f_3`. The constrained variant is CRE32, which is not implemented here. References: Ray, T., & Liew, K. M. (2002). A swarm metaphor for multiobjective design optimization. Engineering Optimization, 34(2), 141-153. https://doi.org/10.1080/03052150210915. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. Args: p (float, optional): the load on the beam (lb). Defaults to 6000.0. l (float, optional): the beam overhang length (in). Defaults to 14.0. e (float, optional): Young's modulus (psi). Defaults to 30.0e6. g (float, optional): the shear modulus (psi). Defaults to 12.0e6. tau_max (float, optional): the maximum allowable shear stress (psi). Defaults to 13600.0. sigma_max (float, optional): the maximum allowable normal stress (psi). Defaults to 30000.0. Returns: Problem: an instance of the welded beam design problem. """ x_1 = Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.125, upperbound=5, initial_value=1.0 ) x_2 = Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.1, upperbound=10, initial_value=5.0 ) x_3 = Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0.1, upperbound=10, initial_value=5.0 ) x_4 = Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=0.125, upperbound=5, initial_value=1.0 ) # The half-sum (x_1 + x_3) / 2 appears in both R and J, so it is written once. half_sum_sq = "((x_1 + x_3) / 2)**2" tau_prime = f"({p} / ({np.sqrt(2.0)} * x_1 * x_2))" moment = f"({p} * ({l} + x_2 / 2))" radius = f"(Sqrt(x_2**2 / 4 + {half_sum_sq}))" polar_moment = f"(2 * ({np.sqrt(2.0)} * x_1 * x_2 * (x_2**2 / 12 + {half_sum_sq})))" tau_double_prime = f"(({moment} * {radius}) / {polar_moment})" tau = ( f"Sqrt({tau_prime}**2 + (2 * {tau_prime} * {tau_double_prime} * x_2) / (2 * {radius}) + {tau_double_prime}**2)" ) sigma = f"((6 * {p} * {l}) / (x_4 * x_3**2))" buckling_load = ( f"(((4.013 * {e} * Sqrt(x_3**2 * x_4**6 / 36)) / {l}**2) * (1 - (x_3 / (2 * {l})) * {np.sqrt(e / (4.0 * g))}))" ) extras = [ ExtraFunction( name="g_1", symbol="g_1", func=f"{tau_max} - {tau}", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ), ExtraFunction( name="g_2", symbol="g_2", func=f"{sigma_max} - {sigma}", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ), ExtraFunction( name="g_3", symbol="g_3", func="x_4 - x_1", is_linear=True, is_convex=True, is_twice_differentiable=True, ), ExtraFunction( name="g_4", symbol="g_4", func=f"{buckling_load} - {p}", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ), ] f_1 = Objective( name="f_1", symbol="f_1", func="1.10471 * x_1**2 * x_2 + 0.04811 * x_3 * x_4 * (14 + x_2)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func=f"({4 * p * l**3 / e}) / (x_4 * x_3**3)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_3 = Objective( name="f_3", symbol="f_3", func=_violation_objective(["g_1", "g_2", "g_3", "g_4"]), objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) return Problem( name="re32", description="The welded beam design problem", variables=[x_1, x_2, x_3, x_4], objectives=[f_1, f_2, f_3], extra_funcs=extras, ) ``` ### re33 ``` re33() -> Problem ``` The disc brake design problem. The first two objectives are the mass of the brake and the minimum stopping time; the third is the sum of the four constraint violations: \[\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = 4.9 \\times 10^{-5}(x_2^2 - x_1^2)(x_4 - 1) \\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = \\frac{9.82 \\times 10^6 (x_2^2 - x_1^2)} {x_3x_4(x_2^3 - x_1^3)} \\ &\\min\_{\\mathbf{x}} & f_3(\\mathbf{x}) & = \\sum\_{i=1}^4 \\max{-g_i(\\mathbf{x}), 0} \\ &\\text{where} & g_1(\\mathbf{x}) & = (x_2 - x_1) - 20 \\geq 0,\\ & & g_2(\\mathbf{x}) & = 0.4 - \\frac{x_3}{3.14(x_2^2 - x_1^2)} \\geq 0, \\ & & g_3(\\mathbf{x}) & = 1 - \\frac{2.22 \\times 10^{-3}x_3(x_2^3 - x_1^3)} {(x_2^2 - x_1^2)^2} \\geq 0, \\ & & g_4(\\mathbf{x}) & = \\frac{2.66 \\times 10^{-2}x_3x_4(x_2^3 - x_1^3)}{x_2^2 - x_1^2} - 900 \\geq 0, \\end{align}\] where (x_1 \\in [55, 80]), (x_2 \\in [75, 110]), (x_3 \\in [1000, 3000]) and (x_4 \\in [11, 20]). The four variables are the inner radius of the discs, the outer radius of the discs, the engaging force, and the number of friction surfaces. The number of friction surfaces is continuous here: the original range is ([2, 20]), but the original problem also constrains (x_4 \\geq 11), so the RE suite folds that bound into the variable range instead of into (f_3). Note Following the RE suite, the returned problem has **no constraints** — the constraint violations are folded into `f_3`. The constrained variant is CRE33, which is not implemented here. References Ray, T., & Liew, K. M. (2002). A swarm metaphor for multiobjective design optimization. Engineering Optimization, 34(2), 141-153. https://doi.org/10.1080/03052150210915. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. Returns: | Name | Type | Description | | --------- | --------- | --------------------------------------------- | | `Problem` | `Problem` | an instance of the disc brake design problem. | Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re33() -> Problem: r"""The disc brake design problem. The first two objectives are the mass of the brake and the minimum stopping time; the third is the sum of the four constraint violations: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = 4.9 \times 10^{-5}(x_2^2 - x_1^2)(x_4 - 1) \\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) & = \frac{9.82 \times 10^6 (x_2^2 - x_1^2)} {x_3x_4(x_2^3 - x_1^3)} \\ &\min_{\mathbf{x}} & f_3(\mathbf{x}) & = \sum_{i=1}^4 \max\{-g_i(\mathbf{x}), 0\} \\ &\text{where} & g_1(\mathbf{x}) & = (x_2 - x_1) - 20 \geq 0,\\ & & g_2(\mathbf{x}) & = 0.4 - \frac{x_3}{3.14(x_2^2 - x_1^2)} \geq 0, \\ & & g_3(\mathbf{x}) & = 1 - \frac{2.22 \times 10^{-3}x_3(x_2^3 - x_1^3)} {(x_2^2 - x_1^2)^2} \geq 0, \\ & & g_4(\mathbf{x}) & = \frac{2.66 \times 10^{-2}x_3x_4(x_2^3 - x_1^3)}{x_2^2 - x_1^2} - 900 \geq 0, \end{align} where $x_1 \in [55, 80]$, $x_2 \in [75, 110]$, $x_3 \in [1000, 3000]$ and $x_4 \in [11, 20]$. The four variables are the inner radius of the discs, the outer radius of the discs, the engaging force, and the number of friction surfaces. The number of friction surfaces is continuous here: the original range is $[2, 20]$, but the original problem also constrains $x_4 \geq 11$, so the RE suite folds that bound into the variable range instead of into $f_3$. Note: Following the RE suite, the returned problem has **no constraints** — the constraint violations are folded into `f_3`. The constrained variant is CRE33, which is not implemented here. References: Ray, T., & Liew, K. M. (2002). A swarm metaphor for multiobjective design optimization. Engineering Optimization, 34(2), 141-153. https://doi.org/10.1080/03052150210915. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. Returns: Problem: an instance of the disc brake design problem. """ x_1 = Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=55, upperbound=80, initial_value=60 ) x_2 = Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=75, upperbound=110, initial_value=90 ) x_3 = Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=1000, upperbound=3000, initial_value=2000, ) x_4 = Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.real, lowerbound=11, upperbound=20, initial_value=15 ) # Squared and cubed radius differences recur in every function below. sq_diff = "(x_2**2 - x_1**2)" cube_diff = "(x_2**3 - x_1**3)" extras = [ ExtraFunction( name="g_1", symbol="g_1", func="(x_2 - x_1) - 20", is_linear=True, is_convex=True, is_twice_differentiable=True, ), ExtraFunction( name="g_2", symbol="g_2", func=f"0.4 - x_3 / (3.14 * {sq_diff})", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ), ExtraFunction( name="g_3", symbol="g_3", func=f"1 - (2.22e-3 * x_3 * {cube_diff}) / {sq_diff}**2", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ), ExtraFunction( name="g_4", symbol="g_4", func=f"(2.66e-2 * x_3 * x_4 * {cube_diff}) / {sq_diff} - 900", is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ), ] f_1 = Objective( name="f_1", symbol="f_1", func=f"4.9e-5 * {sq_diff} * (x_4 - 1)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func=f"(9.82e6 * {sq_diff}) / (x_3 * x_4 * {cube_diff})", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_3 = Objective( name="f_3", symbol="f_3", func=_violation_objective(["g_1", "g_2", "g_3", "g_4"]), objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) return Problem( name="re33", description="The disc brake design problem", variables=[x_1, x_2, x_3, x_4], objectives=[f_1, f_2, f_3], extra_funcs=extras, ) ``` ### re34 ``` re34() -> Problem ``` The vehicle crash worthiness design problem. The implementation of this problem is taken from the vehicle_crashworthiness_problem.py file. Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re34() -> Problem: """The vehicle crash worthiness design problem. The implementation of this problem is taken from the vehicle_crashworthiness_problem.py file. """ return vehicle_crashworthiness() ``` ### re37 ``` re37() -> Problem ``` The rocket injector design problem. The implementation of this problem is taken from the rocket_injector_design_problem.py file. Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re37() -> Problem: """The rocket injector design problem. The implementation of this problem is taken from the rocket_injector_design_problem.py file. """ return rocket_injector_design() ``` ### re41 ``` re41() -> Problem ``` The car side impact design problem. The implementation of this problem is taken from the car_side_impact_problem.py file. Removes the constraints from the problem. Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re41() -> Problem: """The car side impact design problem. The implementation of this problem is taken from the car_side_impact_problem.py file. Removes the constraints from the problem. """ return car_side_impact(three_obj=False).model_copy(update={"constraints": None}) ``` ### re42 ``` re42( round_trip_miles: float = 5000.0, fuel_price: float = 100.0, handling_rate: float = 8000.0, gravity: float = 9.8065, ) -> Problem ``` The conceptual marine design problem. A bulk carrier is sized by its length, beam, depth, draft, speed and block coefficient. The first three objectives are the transportation cost, the light ship weight and the (negated) annual cargo transport capacity; the fourth is the sum of the nine constraint violations: [\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = \\frac{\\text{annual costs}}{\\text{annual cargo}} \\ &\\min\_{\\mathbf{x}} & f_2(\\mathbf{x}) & = W_s + W_o + W_m \\ &\\min\_{\\mathbf{x}} & f_3(\\mathbf{x}) & = -\\text{cargo DWT} \\times \\text{RTPA} \\ &\\min\_{\\mathbf{x}} & f_4(\\mathbf{x}) & = \\sum\_{i=1}^9 \\max{-g_i(\\mathbf{x}), 0} \\ &\\text{where} & g_1 & = L/B - 6 \\geq 0, & g_2 & = 15 - L/D \\geq 0, \\ & & g_3 & = 19 - L/T \\geq 0, & g_4 & = 0.45,\\text{DWT}^{0.31} - T \\geq 0, \\ & & g_5 & = 0.7D + 0.7 - T \\geq 0, & g_6 & = \\text{DWT} - 3,000 \\geq 0, \\ & & g_7 & = 500,000 - \\text{DWT} \\geq 0, & g_8 & = 0.32 - F_n \\geq 0, \\ & & g_9 & = K_B + BM_T - K_G - 0.07B \\geq 0. & \\end{align}] The intermediate quantities — displacement, power, Froude number, the weight and cost breakdowns, the round-trip schedule and the stability terms — are defined as extra functions on the returned problem, one per equation of the source, so they can be inspected alongside the objectives. The decision variables (L, B, D, T, V_k, C_B) are the length, beam, depth, draft, speed and block coefficient, with (L \\in [150, 274.32]), (B \\in [20, 32.31]), (D \\in [13, 25]), (T \\in [10, 11.71]), (V_k \\in [14, 18]) and (C_B \\in [0.63, 0.75]). The annual cargo capacity is maximised in the original formulation and is negated here so that every objective is minimised. Note Following the RE suite, the returned problem has **no constraints** — the constraint violations are folded into `f_4`. The constrained variant is CRE42, which is not implemented here. The upper bound on the deadweight in (g_7) is 500 000, not the 50 000 that the RE reference implementation shipped until it was corrected in 2021. Warning **The number of sea days is (\\text{round trip miles} / 24 \\times V_k), not (\\text{round trip miles} / (24 V_k)).** The second is the dimensionally sensible reading — days at sea should fall as the ship goes faster — but the first is what defines RE42, and it is reproduced here deliberately. Verified against the suite's published ideal point: the objective minima over the box agree to eight significant figures with ((-2756.259, 3962.558, 1947.881, 0)) under this reading, and are wrong by a factor of 400 in (f_3) under the other. Any comparison with published RE42 results needs this equation. A consequence worth knowing before interpreting results: at 3 333 sea days the ship carries more fuel than its deadweight, so the cargo deadweight is negative across the whole reference front. The annual cargo is therefore negative and (f_3 = -\\text{annual cargo}) is positive, which is why the published front has (f_3 \\in [1948, 5195]) rather than the large negative values a physically-sensible schedule would give. References Parsons, M. G., & Scott, R. L. (2004). Formulation of multicriterion design optimization problems for solution with scalar numerical optimization methods. Journal of Ship Research, 48(1), 61-76. https://doi.org/10.5957/jsr.2004.48.1.61. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. Parameters: | Name | Type | Description | Default | | ------------------ | ------- | ---------------------------------------------------------------------------------- | -------- | | `round_trip_miles` | `float` | the length of one round trip (nautical miles). Defaults to 5000.0. | `5000.0` | | `fuel_price` | `float` | the price of fuel per ton. Defaults to 100.0. | `100.0` | | `handling_rate` | `float` | the cargo handling rate in port (tons per day). Defaults to 8000.0. | `8000.0` | | `gravity` | `float` | gravitational acceleration (m/s^2), used in the Froude number. Defaults to 9.8065. | `9.8065` | Returns: | Name | Type | Description | | --------- | --------- | ---------------------------------------------------- | | `Problem` | `Problem` | an instance of the conceptual marine design problem. | Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re42( round_trip_miles: float = 5000.0, fuel_price: float = 100.0, handling_rate: float = 8000.0, gravity: float = 9.8065, ) -> Problem: r"""The conceptual marine design problem. A bulk carrier is sized by its length, beam, depth, draft, speed and block coefficient. The first three objectives are the transportation cost, the light ship weight and the (negated) annual cargo transport capacity; the fourth is the sum of the nine constraint violations: \begin{align} &\min_{\mathbf{x}} & f_1(\mathbf{x}) & = \frac{\text{annual costs}}{\text{annual cargo}} \\ &\min_{\mathbf{x}} & f_2(\mathbf{x}) & = W_s + W_o + W_m \\ &\min_{\mathbf{x}} & f_3(\mathbf{x}) & = -\text{cargo DWT} \times \text{RTPA} \\ &\min_{\mathbf{x}} & f_4(\mathbf{x}) & = \sum_{i=1}^9 \max\{-g_i(\mathbf{x}), 0\} \\ &\text{where} & g_1 & = L/B - 6 \geq 0, & g_2 & = 15 - L/D \geq 0, \\ & & g_3 & = 19 - L/T \geq 0, & g_4 & = 0.45\,\text{DWT}^{0.31} - T \geq 0, \\ & & g_5 & = 0.7D + 0.7 - T \geq 0, & g_6 & = \text{DWT} - 3\,000 \geq 0, \\ & & g_7 & = 500\,000 - \text{DWT} \geq 0, & g_8 & = 0.32 - F_n \geq 0, \\ & & g_9 & = K_B + BM_T - K_G - 0.07B \geq 0. & \end{align} The intermediate quantities — displacement, power, Froude number, the weight and cost breakdowns, the round-trip schedule and the stability terms — are defined as extra functions on the returned problem, one per equation of the source, so they can be inspected alongside the objectives. The decision variables $L, B, D, T, V_k, C_B$ are the length, beam, depth, draft, speed and block coefficient, with $L \in [150, 274.32]$, $B \in [20, 32.31]$, $D \in [13, 25]$, $T \in [10, 11.71]$, $V_k \in [14, 18]$ and $C_B \in [0.63, 0.75]$. The annual cargo capacity is maximised in the original formulation and is negated here so that every objective is minimised. Note: Following the RE suite, the returned problem has **no constraints** — the constraint violations are folded into `f_4`. The constrained variant is CRE42, which is not implemented here. The upper bound on the deadweight in $g_7$ is 500 000, not the 50 000 that the RE reference implementation shipped until it was corrected in 2021. Warning: **The number of sea days is $\text{round trip miles} / 24 \times V_k$, not $\text{round trip miles} / (24 V_k)$.** The second is the dimensionally sensible reading — days at sea should fall as the ship goes faster — but the first is what defines RE42, and it is reproduced here deliberately. Verified against the suite's published ideal point: the objective minima over the box agree to eight significant figures with $(-2756.259, 3962.558, 1947.881, 0)$ under this reading, and are wrong by a factor of 400 in $f_3$ under the other. Any comparison with published RE42 results needs this equation. A consequence worth knowing before interpreting results: at 3 333 sea days the ship carries more fuel than its deadweight, so the cargo deadweight is negative across the whole reference front. The annual cargo is therefore negative and $f_3 = -\text{annual cargo}$ is positive, which is why the published front has $f_3 \in [1948, 5195]$ rather than the large negative values a physically-sensible schedule would give. References: Parsons, M. G., & Scott, R. L. (2004). Formulation of multicriterion design optimization problems for solution with scalar numerical optimization methods. Journal of Ship Research, 48(1), 61-76. https://doi.org/10.5957/jsr.2004.48.1.61. Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. https://doi.org/10.1016/j.asoc.2020.106078. Args: round_trip_miles (float, optional): the length of one round trip (nautical miles). Defaults to 5000.0. fuel_price (float, optional): the price of fuel per ton. Defaults to 100.0. handling_rate (float, optional): the cargo handling rate in port (tons per day). Defaults to 8000.0. gravity (float, optional): gravitational acceleration (m/s^2), used in the Froude number. Defaults to 9.8065. Returns: Problem: an instance of the conceptual marine design problem. """ # x_1 = L, x_2 = B, x_3 = D, x_4 = T, x_5 = V_k, x_6 = C_B. bounds = [ ("x_1", "length", 150.0, 274.32), ("x_2", "beam", 20.0, 32.31), ("x_3", "depth", 13.0, 25.0), ("x_4", "draft", 10.0, 11.71), ("x_5", "speed", 14.0, 18.0), ("x_6", "block coefficient", 0.63, 0.75), ] variables = [ Variable( name=name, symbol=symbol, variable_type=VariableTypeEnum.real, lowerbound=lower, upperbound=upper, initial_value=(lower + upper) / 2, ) for symbol, name, lower, upper in bounds ] def extra(symbol: str, func: str, *, is_linear: bool = False) -> ExtraFunction: return ExtraFunction( name=symbol, symbol=symbol, func=func, is_linear=is_linear, is_convex=False, # Not checked is_twice_differentiable=True, ) # One extra function per equation of the source, in dependency order: each may refer to the ones # above it. Written this way rather than as one substituted expression because the source defines # the ship this way, and because the intermediate values are worth reading off a solution. extras = [ extra("displacement", "1.025 * x_1 * x_2 * x_4 * x_6"), extra("froude", f"(0.5144 * x_5) / Sqrt({gravity} * x_1)"), # The admiralty coefficient is a quadratic in the block coefficient. extra("coef_a", "4977.06 * x_6**2 - 8105.61 * x_6 + 4456.51"), extra("coef_b", "-10847.2 * x_6**2 + 12817 * x_6 - 6960.32"), extra("power", f"(displacement**{2 / 3} * x_5**3) / (coef_a + coef_b * froude)"), extra("weight_steel", "0.034 * x_1**1.7 * x_2**0.7 * x_3**0.4 * x_6**0.5"), extra("weight_outfit", "1.0 * x_1**0.8 * x_2**0.6 * x_3**0.3 * x_6**0.1"), extra("weight_machinery", "0.17 * power**0.9"), extra("light_ship", "weight_steel + weight_outfit + weight_machinery", is_linear=True), extra("deadweight", "displacement - light_ship", is_linear=True), extra("ship_cost", "1.3 * (2000 * weight_steel**0.85 + 3500 * weight_outfit + 2400 * power**0.8)"), extra("capital_costs", "0.2 * ship_cost", is_linear=True), extra("running_costs", "40000 * deadweight**0.3"), extra("daily_consumption", "(0.19 * power * 24) / 1000 + 0.2", is_linear=True), # Transcribed exactly as the RE suite states it: (round trip miles / 24) * speed. Dividing by # the speed instead would be the dimensionally sensible reading, but it is not this problem — # see the note in the docstring. The parentheses are load-bearing: the expression parser reads # "a / b * c" as "a / (b * c)", which is the sensible reading and the wrong problem. extra("sea_days", f"({round_trip_miles} / 24) * x_5"), extra("fuel_cost", f"1.05 * daily_consumption * sea_days * {fuel_price}"), extra("port_cost", "6.3 * deadweight**0.8"), extra("fuel_carried", "daily_consumption * (sea_days + 5)"), extra("miscellaneous_deadweight", "2 * deadweight**0.5"), extra("cargo_deadweight", "deadweight - fuel_carried - miscellaneous_deadweight", is_linear=True), extra("port_days", f"2 * (cargo_deadweight / {handling_rate} + 0.5)", is_linear=True), extra("round_trips_per_year", "350 / (sea_days + port_days)"), extra("voyage_costs", "(fuel_cost + port_cost) * round_trips_per_year"), extra("annual_costs", "capital_costs + running_costs + voyage_costs", is_linear=True), extra("annual_cargo", "cargo_deadweight * round_trips_per_year"), # Stability: centre of buoyancy, metacentric radius and centre of gravity. extra("centre_of_buoyancy", "0.53 * x_4", is_linear=True), extra("metacentric_radius", "((0.085 * x_6 - 0.002) * x_2**2) / (x_4 * x_6)"), extra("centre_of_gravity", "1 + 0.52 * x_3", is_linear=True), extra("g_1", "x_1 / x_2 - 6"), extra("g_2", "15 - x_1 / x_3"), extra("g_3", "19 - x_1 / x_4"), extra("g_4", "0.45 * deadweight**0.31 - x_4"), extra("g_5", "0.7 * x_3 + 0.7 - x_4", is_linear=True), extra("g_6", "deadweight - 3000", is_linear=True), extra("g_7", "500000 - deadweight", is_linear=True), extra("g_8", "0.32 - froude"), extra("g_9", "centre_of_buoyancy + metacentric_radius - centre_of_gravity - 0.07 * x_2", is_linear=True), ] f_1 = Objective( name="f_1", symbol="f_1", func="annual_costs / annual_cargo", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func="light_ship", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_3 = Objective( name="f_3", symbol="f_3", func="-annual_cargo", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=True, ) f_4 = Objective( name="f_4", symbol="f_4", func=_violation_objective([f"g_{i}" for i in range(1, 10)]), objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=False, # Not checked is_twice_differentiable=False, ) return Problem( name="re42", description="The conceptual marine design problem", variables=variables, objectives=[f_1, f_2, f_3, f_4], extra_funcs=extras, ) ``` ### re61 ``` re61() -> Problem ``` The water management design problem. The implementation of this problem is taken from the water_management_problem.py file. Removes the constraints from the problem. Source code in `desdeo/problem/testproblems/re_problem.py` ``` def re61() -> Problem: """The water management design problem. The implementation of this problem is taken from the water_management_problem.py file. Removes the constraints from the problem. """ return water_management(six_obj=True).model_copy(update={"constraints": None}) ``` ### river_pollution_problem ``` river_pollution_problem( *, five_objective_variant: bool = True ) -> Problem ``` Create a pydantic dataclass representation of the river pollution problem with either five or four variables. The objective functions "DO city" ((f_1)), "DO municipality" ((f_2), and "ROI fishery" ()f_3() and "ROI city" ()f_4() are to be maximized. If the four variant problem is used, the the "BOD deviation" objective function ()f_5$) is not present, but if it is, it is to be minimized. The problem is defined as follows: [\\begin{align\*} \\max f_1(x) &= 4.07 + 2.27 x_1 \\ \\max f_2(x) &= 2.60 + 0.03 x_1 + 0.02 x_2 + \\frac{0.01}{1.39 - x_1^2} + \\frac{0.30}{1.39 - x_2^2} \\ \\max f_3(x) &= 8.21 - \\frac{0.71}{1.09 - x_1^2} \\ \\max f_4(x) &= 0.96 - \\frac{0.96}{1.09 - x_2^2} \\ \\min f_5(x) &= \\max(|x_1 - 0.65|, |x_2 - 0.65|) \\ \\text{s.t.}\\quad & 0.3 \\leq x_1 \\leq 1.0,\\ & 0.3 \\leq x_2 \\leq 1.0,\\ \\end{align\*}] where the fifth objective is part of the problem definition only if `five_objective_variant = True`. Parameters: | Name | Type | Description | Default | | ------------------------ | ------ | ------------------------------------------------------------------------------------------- | ------- | | `five_objective_variant` | `bool` | Whether to use the five-objective function variant of the problem or not. Defaults to True. | `True` | Returns: | Name | Type | Description | | --------- | --------- | ---------------------------- | | `Problem` | `Problem` | the river pollution problem. | References Narula, Subhash C., and HRoland Weistroffer. "A flexible method for nonlinear multicriteria decision-making problems." IEEE Transactions on Systems, Man, and Cybernetics 19.4 (1989): 883-887. Miettinen, Kaisa, and Marko M. Mäkelä. "Interactive method NIMBUS for nondifferentiable multiobjective optimization problems." Multicriteria Analysis: Proceedings of the XIth International Conference on MCDM, 1-6 August 1994, Coimbra, Portugal. Berlin, Heidelberg: Springer Berlin Heidelberg, 1997. Source code in `desdeo/problem/testproblems/river_pollution_problems.py` ``` def river_pollution_problem(*, five_objective_variant: bool = True) -> Problem: r"""Create a pydantic dataclass representation of the river pollution problem with either five or four variables. The objective functions "DO city" ($f_1$), "DO municipality" ($f_2), and "ROI fishery" ($f_3$) and "ROI city" ($f_4$) are to be maximized. If the four variant problem is used, the the "BOD deviation" objective function ($f_5$) is not present, but if it is, it is to be minimized. The problem is defined as follows: \begin{align*} \max f_1(x) &= 4.07 + 2.27 x_1 \\ \max f_2(x) &= 2.60 + 0.03 x_1 + 0.02 x_2 + \frac{0.01}{1.39 - x_1^2} + \frac{0.30}{1.39 - x_2^2} \\ \max f_3(x) &= 8.21 - \frac{0.71}{1.09 - x_1^2} \\ \max f_4(x) &= 0.96 - \frac{0.96}{1.09 - x_2^2} \\ \min f_5(x) &= \max(|x_1 - 0.65|, |x_2 - 0.65|) \\ \text{s.t.}\quad & 0.3 \leq x_1 \leq 1.0,\\ & 0.3 \leq x_2 \leq 1.0,\\ \end{align*} where the fifth objective is part of the problem definition only if `five_objective_variant = True`. Args: five_objective_variant (bool, optional): Whether to use the five-objective function variant of the problem or not. Defaults to True. Returns: Problem: the river pollution problem. References: Narula, Subhash C., and HRoland Weistroffer. "A flexible method for nonlinear multicriteria decision-making problems." IEEE Transactions on Systems, Man, and Cybernetics 19.4 (1989): 883-887. Miettinen, Kaisa, and Marko M. Mäkelä. "Interactive method NIMBUS for nondifferentiable multiobjective optimization problems." Multicriteria Analysis: Proceedings of the XIth International Conference on MCDM, 1-6 August 1994, Coimbra, Portugal. Berlin, Heidelberg: Springer Berlin Heidelberg, 1997. """ variable_1 = Variable( name="BOD", symbol="x_1", variable_type="real", lowerbound=0.3, upperbound=1.0, initial_value=0.65 ) variable_2 = Variable( name="DO", symbol="x_2", variable_type="real", lowerbound=0.3, upperbound=1.0, initial_value=0.65 ) f_1 = "4.07 + 2.27 * x_1" f_2 = "2.60 + 0.03 * x_1 + 0.02 * x_2 + 0.01 / (1.39 - x_1**2) + 0.30 / (1.39 - x_2**2)" f_3 = "8.21 - 0.71 / (1.09 - x_1**2)" f_4 = "0.96 - 0.96 / (1.09 - x_2**2)" f_5 = "Max(Abs(x_1 - 0.65), Abs(x_2 - 0.65))" objective_1 = Objective( name="DO city", symbol="f_1", func=f_1, maximize=True, ideal=6.34, nadir=4.75, is_convex=True, is_linear=True, is_twice_differentiable=True, ) objective_2 = Objective( name="DO municipality", symbol="f_2", func=f_2, maximize=True, ideal=3.44, nadir=2.85, is_convex=False, is_linear=False, is_twice_differentiable=True, ) objective_3 = Objective( name="ROI fishery", symbol="f_3", func=f_3, maximize=True, ideal=7.5, nadir=0.32, is_convex=True, is_linear=False, is_twice_differentiable=True, ) objective_4 = Objective( name="ROI city", symbol="f_4", func=f_4, maximize=True, ideal=0, nadir=-9.70, is_convex=True, is_linear=False, is_twice_differentiable=True, ) objective_5 = Objective( name="BOD deviation", symbol="f_5", func=f_5, maximize=False, ideal=0, nadir=0.35, is_convex=False, is_linear=False, is_twice_differentiable=False, ) objectives = ( [objective_1, objective_2, objective_3, objective_4, objective_5] if five_objective_variant else [objective_1, objective_2, objective_3, objective_4] ) return Problem( name="The river pollution problem", description="The river pollution problem to maximize return of investments (ROI) and dissolved oxygen (DO).", variables=[variable_1, variable_2], objectives=objectives, ) ``` ### river_pollution_problem_discrete ``` river_pollution_problem_discrete( *, five_objective_variant: bool = True ) -> Problem ``` Create a pydantic dataclass representation of the river pollution problem with either five or four variables. The objective functions "DO city" ((f_1)), "DO municipality" ((f_2), and "ROI fishery" ()f_3() and "ROI city" ()f_4() are to be maximized. If the four variant problem is used, the the "BOD deviation" objective function ()f_5$) is not present, but if it is, it is to be minimized. This version of the problem uses discrete representation of the variables and objectives and does not provide the analytical functions for the objectives. Parameters: | Name | Type | Description | Default | | ------------------------ | ------ | ------------------------------------------------------------------------------------------- | ------- | | `five_objective_variant` | `bool` | Whether to use the five-objective function variant of the problem or not. Defaults to True. | `True` | Returns: | Name | Type | Description | | --------- | --------- | ---------------------------- | | `Problem` | `Problem` | the river pollution problem. | References Narula, Subhash C., and HRoland Weistroffer. "A flexible method for nonlinear multicriteria decision-making problems." IEEE Transactions on Systems, Man, and Cybernetics 19.4 (1989): 883-887. Miettinen, Kaisa, and Marko M. Mäkelä. "Interactive method NIMBUS for nondifferentiable multiobjective optimization problems." Multicriteria Analysis: Proceedings of the XIth International Conference on MCDM, 1-6 August 1994, Coimbra, Portugal. Berlin, Heidelberg: Springer Berlin Heidelberg, 1997. Source code in `desdeo/problem/testproblems/river_pollution_problems.py` ``` def river_pollution_problem_discrete(*, five_objective_variant: bool = True) -> Problem: """Create a pydantic dataclass representation of the river pollution problem with either five or four variables. The objective functions "DO city" ($f_1$), "DO municipality" ($f_2), and "ROI fishery" ($f_3$) and "ROI city" ($f_4$) are to be maximized. If the four variant problem is used, the the "BOD deviation" objective function ($f_5$) is not present, but if it is, it is to be minimized. This version of the problem uses discrete representation of the variables and objectives and does not provide the analytical functions for the objectives. Args: five_objective_variant (bool, optional): Whether to use the five-objective function variant of the problem or not. Defaults to True. Returns: Problem: the river pollution problem. References: Narula, Subhash C., and HRoland Weistroffer. "A flexible method for nonlinear multicriteria decision-making problems." IEEE Transactions on Systems, Man, and Cybernetics 19.4 (1989): 883-887. Miettinen, Kaisa, and Marko M. Mäkelä. "Interactive method NIMBUS for nondifferentiable multiobjective optimization problems." Multicriteria Analysis: Proceedings of the XIth International Conference on MCDM, 1-6 August 1994, Coimbra, Portugal. Berlin, Heidelberg: Springer Berlin Heidelberg, 1997. """ filename = "datasets/river_poll_4_objs.csv" true_var_names = {"x_1": "BOD", "x_2": "DO"} true_obj_names = {"f1": "DO city", "f2": "DO municipality", "f3": "ROI fishery", "f4": "ROI city"} if five_objective_variant: filename = "datasets/river_poll_5_objs.csv" true_obj_names["f5"] = "BOD deviation" path = Path(__file__).parent.parent.parent.parent / filename data = pl.read_csv(path, has_header=True) variables = [ Variable( name=true_var_names[varName], symbol=varName, variable_type=VariableTypeEnum.real, lowerbound=0.3, upperbound=1.0, initial_value=0.65, ) for varName in true_var_names ] maximize = {"f1": True, "f2": True, "f3": True, "f4": True, "f5": False} ideal = {objName: (data[objName].max() if maximize[objName] else data[objName].min()) for objName in true_obj_names} nadir = {objName: (data[objName].min() if maximize[objName] else data[objName].max()) for objName in true_obj_names} units = {"f1": "mg/L", "f2": "mg/L", "f3": "%", "f4": "%", "f5": "mg/L"} objectives = [ Objective( name=true_obj_names[objName], symbol=objName, func=None, unit=units[objName], objective_type=ObjectiveTypeEnum.data_based, maximize=maximize[objName], ideal=ideal[objName], nadir=nadir[objName], ) for objName in true_obj_names ] discrete_def = DiscreteRepresentation( variable_values=data[list(true_var_names.keys())].to_dict(), objective_values=data[list(true_obj_names.keys())].to_dict(), ) return Problem( name="The river pollution problem (Discrete)", description="The river pollution problem to maximize return of investments (ROI) and dissolved oxygen (DO).", variables=variables, objectives=objectives, discrete_representation=discrete_def, ) ``` ### river_pollution_scenario ``` river_pollution_scenario() -> Problem ``` Defines the scenario-based uncertain variant of the river pollution problem. The river pollution problem considers a river close to a city. There are two sources of pollution: industrial pollution from a fishery and municipal waste from the city. Two treatment plants (in the fishery and the city) are responsible for managing the pollution. Pollution is reported in pounds of biochemical oxygen demanding material (BOD), and water quality is measured in dissolved oxygen concentration (DO). Cleaning water in the city increases the tax rate, and cleaning in the fishery reduces the return on investment. The problem is to improve the DO level in the city and at the municipality border (`f1` and `f2`, respectively), while, at the same time, maximizing the percent return on investment at the fishery (`f3`) and minimizing additions to the city tax (`f4`). Decision variables are: - `x1`: The proportional amount of BOD removed from water after the fishery (treatment plant 1). - `x2`: The proportional amount of BOD removed from water after the city (treatment plant 2). The original problem considered specific values for all parameters. However, in this formulation, some parameters are deeply uncertain, and only a range of plausible values is known for each. These deeply uncertain parameters are as follows: - `α ∈ [3, 4.24]`: Water quality index after the fishery. - `β ∈ [2.25, 2.4]`: BOD reduction rate at treatment plant 1 (after the fishery). - `δ ∈ [0.075, 0.092]`: BOD reduction rate at treatment plant 2 (after the city). - `ξ ∈ [0.067, 0.083]`: Effective rate of BOD reduction at treatment plant 1 after the city. - `η ∈ [1.2, 1.50]`: Parameter used to calculate the effective BOD reduction rate at the second treatment plant. - `r ∈ [5.1, 12.5]`: Investment return rate. The uncertain version of the river problem is formulated as follows: \[ \\begin{equation} \\begin{array}{rll} \\text{maximize} & f_1(\\mathbf{x}) = & \\alpha + \\left(\\log\\left(\\left(\\frac{\\beta}{2} - 1.14\\right)^2\\right) + \\beta^3\\right) x_1 \\\\ \\text{maximize} & f_2(\\mathbf{x}) = & \\gamma + \\delta x_1 + \\xi x_2 + \\frac{0.01}{\\eta - x_1^2} * \\frac{0.30}{\\eta - x_2^2} \\\\ \\text{maximize} & f_3(\\mathbf{x}) = & r - \\frac{0.71}{1.09 - x_1^2} \\\\ \\text{minimize} & f_4(\\mathbf{x}) = & -0.96 + \\frac{0.96}{1.09 - x_2^2} \\\\ \\text{subject to} & & 0.3 \\leq x_1, x_2 \\leq 1.0. \\end{array} \\end{equation} \] where (\\gamma = \\log\\left(\\frac{\\alpha}{2} - 1\\right) + \\frac{\\alpha}{2} + 1.5). Returns: | Name | Type | Description | | --------------- | --------- | ------------------------------------------- | | `ScenarioModel` | `Problem` | the scenario-based river pollution problem. | References Narula, Subhash C., and HRoland Weistroffer. "A flexible method for nonlinear multicriteria decision-making problems." IEEE Transactions on Systems, Man, and Cybernetics 19.4 (1989): 883-887. Miettinen, Kaisa, and Marko M. Mäkelä. "Interactive method NIMBUS for nondifferentiable multiobjective optimization problems." Multicriteria Analysis: Proceedings of the XIth International Conference on MCDM, 1-6 August 1994, Coimbra, Portugal. Berlin, Heidelberg: Springer Berlin Heidelberg, 1997. Source code in `desdeo/problem/testproblems/river_pollution_problems.py` ``` def river_pollution_scenario() -> Problem: r"""Defines the scenario-based uncertain variant of the river pollution problem. The river pollution problem considers a river close to a city. There are two sources of pollution: industrial pollution from a fishery and municipal waste from the city. Two treatment plants (in the fishery and the city) are responsible for managing the pollution. Pollution is reported in pounds of biochemical oxygen demanding material (BOD), and water quality is measured in dissolved oxygen concentration (DO). Cleaning water in the city increases the tax rate, and cleaning in the fishery reduces the return on investment. The problem is to improve the DO level in the city and at the municipality border (`f1` and `f2`, respectively), while, at the same time, maximizing the percent return on investment at the fishery (`f3`) and minimizing additions to the city tax (`f4`). Decision variables are: * `x1`: The proportional amount of BOD removed from water after the fishery (treatment plant 1). * `x2`: The proportional amount of BOD removed from water after the city (treatment plant 2). The original problem considered specific values for all parameters. However, in this formulation, some parameters are deeply uncertain, and only a range of plausible values is known for each. These deeply uncertain parameters are as follows: * `α ∈ [3, 4.24]`: Water quality index after the fishery. * `β ∈ [2.25, 2.4]`: BOD reduction rate at treatment plant 1 (after the fishery). * `δ ∈ [0.075, 0.092]`: BOD reduction rate at treatment plant 2 (after the city). * `ξ ∈ [0.067, 0.083]`: Effective rate of BOD reduction at treatment plant 1 after the city. * `η ∈ [1.2, 1.50]`: Parameter used to calculate the effective BOD reduction rate at the second treatment plant. * `r ∈ [5.1, 12.5]`: Investment return rate. The uncertain version of the river problem is formulated as follows: $$ \\begin{equation} \\begin{array}{rll} \\text{maximize} & f_1(\\mathbf{x}) = & \\alpha + \\left(\\log\\left(\\left(\\frac{\\beta}{2} - 1.14\\right)^2\\right) + \\beta^3\\right) x_1 \\\\ \\text{maximize} & f_2(\\mathbf{x}) = & \\gamma + \\delta x_1 + \\xi x_2 + \\frac{0.01}{\\eta - x_1^2} + \\frac{0.30}{\\eta - x_2^2} \\\\ \\text{maximize} & f_3(\\mathbf{x}) = & r - \\frac{0.71}{1.09 - x_1^2} \\\\ \\text{minimize} & f_4(\\mathbf{x}) = & -0.96 + \\frac{0.96}{1.09 - x_2^2} \\\\ \\text{subject to} & & 0.3 \\leq x_1, x_2 \\leq 1.0. \\end{array} \\end{equation} $$ where $\\gamma = \\log\\left(\\frac{\\alpha}{2} - 1\\right) + \\frac{\\alpha}{2} + 1.5$. Returns: ScenarioModel: the scenario-based river pollution problem. References: Narula, Subhash C., and HRoland Weistroffer. "A flexible method for nonlinear multicriteria decision-making problems." IEEE Transactions on Systems, Man, and Cybernetics 19.4 (1989): 883-887. Miettinen, Kaisa, and Marko M. Mäkelä. "Interactive method NIMBUS for nondifferentiable multiobjective optimization problems." Multicriteria Analysis: Proceedings of the XIth International Conference on MCDM, 1-6 August 1994, Coimbra, Portugal. Berlin, Heidelberg: Springer Berlin Heidelberg, 1997. """ # noqa: RUF002 num_scenarios = 6 scenario_key_stub = "scenario" # defining scenario parameters alpha_values = [4.070, 3.868, 3.620, 3.372, 3.124, 4.116] beta_values = [2.270, 2.262, 2.278, 2.254, 2.270, 2.286] delta_values = [0.0800, 0.0869, 0.0835, 0.0903, 0.0801, 0.0767] xi_values = [0.0750, 0.0782, 0.0750, 0.0814, 0.0686, 0.0718] eta_values = [1.39, 1.47, 1.23, 1.35, 1.29, 1.41] r_values = [8.21, 10.28, 5.84, 11.76, 7.32, 8.80] # each scenario parameter is defined as its own tensor constant alpha_constant = TensorConstant( name="Water quality index after fishery", symbol="alpha", shape=[num_scenarios], values=alpha_values ) beta_constant = TensorConstant( name="BOD reduction rate at treatment plant 1 (after the fishery)", symbol="beta", shape=[num_scenarios], values=beta_values, ) delta_constant = TensorConstant( name="BOD reduction rate at treatment plant 2 (after the city)", symbol="delta", shape=[num_scenarios], values=delta_values, ) xi_constant = TensorConstant( name="The effective rate of BOD reduction at treatment plant 1 (after the city)", symbol="xi", shape=[num_scenarios], values=xi_values, ) eta_constant = TensorConstant( name="The effective rate of BOD reduction rate at plant 2 (after the fishery)", symbol="eta", shape=[num_scenarios], values=eta_values, ) r_constant = TensorConstant( name="Investment return rate", symbol="r", shape=[num_scenarios], values=r_values, ) constants = [alpha_constant, beta_constant, delta_constant, xi_constant, eta_constant, r_constant] # define variables x1 = Variable( name="BOD removed after fishery", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.3, upperbound=1.0, ) x2 = Variable( name="BOD removed after city", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.3, upperbound=1.0, ) variables = [x1, x2] f4_expr = "-0.96 + 0.96/(1.09 - x_2**2)" f4 = Objective( name="Addition to city tax", symbol="f4", func=f4_expr, objective_type=ObjectiveTypeEnum.analytical, maximize=False, is_linear=False, is_convex=False, is_twice_differentiable=True, ) base_problem = Problem( name="Scenario-based river pollution problem", description="The scenario-based river pollution problem", constants=constants, variables=variables, objectives=[f4], ) # Build per-scenario objective pool and scenario definitions pool_objectives = [] scenarios = {} for i in range(num_scenarios): scenario_key = f"{scenario_key_stub}_{i + 1}" gamma_expr = f"Ln(alpha[{i + 1}]/2 - 1) + alpha[{i + 1}]/2 + 1.5" f1_expr = f"alpha[{i + 1}] + (Ln((beta[{i + 1}]/2 - 1.14)**2) + beta[{i + 1}]**3)*x_1" f2_expr = ( f"{gamma_expr} + delta[{i + 1}]*x_1 + xi[{i + 1}]*x_2 + 0.01/(eta[{i + 1}] - x_1**2) " f"+ 0.3/(eta[{i + 1}] - x_2**2)" ) f3_expr = f"r[{i + 1}] - 0.71/(1.09 - x_1**2)" f1 = Objective( name="DO level city", symbol=f"f1_{i + 1}", func=f1_expr, objective_type=ObjectiveTypeEnum.analytical, maximize=True, is_linear=False, is_convex=False, is_twice_differentiable=True, ) f2 = Objective( name="DO level fishery", symbol=f"f2_{i + 1}", func=f2_expr, objective_type=ObjectiveTypeEnum.analytical, maximize=True, is_linear=False, is_convex=False, is_twice_differentiable=True, ) f3 = Objective( name="Return of investment", symbol=f"f3_{i + 1}", func=f3_expr, objective_type=ObjectiveTypeEnum.analytical, maximize=True, is_linear=False, is_convex=False, is_twice_differentiable=True, ) base_idx = i * 3 pool_objectives.extend([f1, f2, f3]) scenarios[scenario_key] = Scenario( objectives={f1.symbol: base_idx, f2.symbol: base_idx + 1, f3.symbol: base_idx + 2} ) return ScenarioModel( scenario_tree=[f"{scenario_key_stub}_{i + 1}" for i in range(num_scenarios)], base_problem=base_problem, objectives=pool_objectives, scenarios=scenarios, ) ``` ### rocket_injector_design ``` rocket_injector_design(original_version=False) -> Problem ``` The rocket injector design problem as published in Vaidyanathan, et al. (2003). The original version of the problem has 4 objectives. In Goel et al. (2007), the TW4 objective is dropped due to high correlation with one of the other objectives. Hence, the default version of the problem is the modified version with 3 objectives. Parameters: | Name | Type | Description | Default | | ------------------ | ------ | --------------------------------------------------------------------------- | ------- | | `original_version` | `bool` | If True, the original version of the problem with 4 objectives is returned. | `False` | References R. Vaidyanathan, K. Tucker, N. Papila, W. Shyy, CFD-Based Design Optimization For Single Element Rocket Injector, in: AIAA Aerospace Sciences Meeting, 2003, pp. 1-21. Goel, T., Vaidyanathan, R., Haftka, R. T., Shyy, W., Queipo, N. V., & Tucker, K. (2007). Response surface approximation of Pareto optimal front in multi-objective optimization. Computer methods in applied mechanics and engineering, 196(4-6), 879-893. Returns: | Name | Type | Description | | --------- | --------- | ----------------------------------- | | `Problem` | `Problem` | The rocket injector design problem. | Source code in `desdeo/problem/testproblems/rocket_injector_design_problem.py` ``` def rocket_injector_design(original_version=False) -> Problem: """The rocket injector design problem as published in Vaidyanathan, et al. (2003). The original version of the problem has 4 objectives. In Goel et al. (2007), the TW4 objective is dropped due to high correlation with one of the other objectives. Hence, the default version of the problem is the modified version with 3 objectives. Args: original_version (bool): If True, the original version of the problem with 4 objectives is returned. References: R. Vaidyanathan, K. Tucker, N. Papila, W. Shyy, CFD-Based Design Optimization For Single Element Rocket Injector, in: AIAA Aerospace Sciences Meeting, 2003, pp. 1-21. Goel, T., Vaidyanathan, R., Haftka, R. T., Shyy, W., Queipo, N. V., & Tucker, K. (2007). Response surface approximation of Pareto optimal front in multi-objective optimization. Computer methods in applied mechanics and engineering, 196(4-6), 879-893. Returns: Problem: The rocket injector design problem. """ # Variables alpha = Variable(name="alpha", symbol="a", variable_type=VariableTypeEnum.real, lowerbound=0.0, upperbound=1.0) deltaha = Variable( name="deltaHA", symbol="DHA", variable_type=VariableTypeEnum.real, lowerbound=0.0, upperbound=1.0 ) deltaoa = Variable( name="deltaOA", symbol="DOA", variable_type=VariableTypeEnum.real, lowerbound=0.0, upperbound=1.0 ) optt = Variable(name="OPTT", symbol="OPTT", variable_type=VariableTypeEnum.real, lowerbound=0.0, upperbound=1.0) # Objectives tfmax_eqn = """ 0.692+ 0.477 * a- 0.687 * DHA- 0.080 * DOA- 0.0650 * OPTT- 0.167 * a * a- 0.0129 * DHA * a + 0.0796 * DHA * DHA- 0.0634 * DOA * a- 0.0257 * DOA * DHA+ 0.0877 * DOA * DOA- 0.0521 * OPTT * a + 0.00156 * OPTT * DHA+ 0.00198 * OPTT * DOA+ 0.0184 * OPTT * OPTT """ xccmax_eqn = """ 0.153- 0.322 * a+ 0.396 * DHA+ 0.424 * DOA+ 0.0226 * OPTT+ 0.175 * a * a + 0.0185 * DHA * a- 0.0701 * DHA * DHA- 0.251 * DOA * a+ 0.179 * DOA * DHA+ 0.0150 * DOA * DOA + 0.0134 * OPTT * a+ 0.0296 * OPTT * DHA+ 0.0752 * OPTT * DOA+ 0.0192 * OPTT * OPTT """ ttmax_eqn = """ 0.370- 0.205 * a+ 0.0307 * DHA+ 0.108 * DOA+ 1.019 * OPTT- 0.135 * a * a+ 0.0141 * DHA * a + 0.0998 * DHA * DHA+ 0.208 * DOA * a- 0.0301 * DOA * DHA- 0.226 * DOA * DOA+ 0.353 * OPTT * a - 0.0497 * OPTT * DOA- 0.423 * OPTT * OPTT+ 0.202 * DHA * a * a- 0.281 * DOA * a * a - 0.342 * DHA * DHA * a- 0.245 * DHA * DHA * DOA+ 0.281 * DOA * DOA * DHA- 0.184 * OPTT * OPTT * a - 0.281 * DHA * a * DOA """ tw4_eqn = """ 0.758 + 0.358 * a - 0.807 * DHA + 0.0925 * DOA - 0.0468 * OPTT - 0.172 * a * a + 0.0106 * DHA * a + 0.0697 * DHA * DHA - 0.146 * DOA * a - 0.0416 * DOA * DHA + 0.102 * DOA * DOA - 0.0694 * OPTT * a - 0.00503 * OPTT * DHA + 0.0151 * OPTT * DOA + 0.0173 * OPTT * OPTT """ # The ideal and nadir values are estimates. If you get a better estimate, feel free to update them. tf_max = Objective( name="TF_max", symbol="TF_max", func=tfmax_eqn, maximize=False, is_linear=False, is_convex=False, is_twice_differentiable=True, ideal=-0.008907, nadir=1.002000, ) xcc_max = Objective( name="Xcc_max", symbol="Xcc_max", func=xccmax_eqn, maximize=False, is_linear=False, is_convex=False, is_twice_differentiable=True, ideal=0.004883, nadir=1.075655, ) tt_max = Objective( name="TT_max", symbol="TT_max", func=ttmax_eqn, maximize=False, is_linear=False, is_convex=False, is_twice_differentiable=True, ideal=-0.419077, nadir=1.092842, ) tw4 = Objective( name="TW4", symbol="TW4", func=tw4_eqn, maximize=False, is_linear=False, is_convex=False, is_twice_differentiable=True, ideal=-0.013602, nadir=0.244688, ) if original_version: # NOQA:SIM108 objectives = [tf_max, tw4, tt_max, xcc_max] else: objectives = [tf_max, tt_max, xcc_max] return Problem( name="Rocket Injector Design Problem", description=( "R. Vaidyanathan, K. Tucker, N. Papila, W. Shyy, CFD-Based Design Optimization For Single Element" " Rocket Injector, in: AIAA Aerospace Sciences Meeting, 2003, pp. 1-21." ), variables=[alpha, deltaha, deltaoa, optt], objectives=objectives, ) ``` ### simple_constrained_quadratic_tensor_test_problem ``` simple_constrained_quadratic_tensor_test_problem( dqp=False, ) -> Problem ``` Defines a simple constrained quadratic problem with tensor variables, suitable for testing purposes. Source code in `desdeo/problem/testproblems/simple_problem.py` ``` def simple_constrained_quadratic_tensor_test_problem(dqp=False) -> Problem: """Defines a simple constrained quadratic problem with tensor variables, suitable for testing purposes.""" xvar = TensorVariable( name="X", symbol="X", variable_type=VariableTypeEnum.real, shape=[ 2, ], initial_values=[1, 1], lowerbounds=[-10, -10], upperbounds=[10, 10], ) mmult = TensorConstant( name="Mmult", symbol="A", shape=[2, 2], values=[[1, 0.5], [0.5, 1]], ) bvector = TensorConstant( name="mcon", symbol="b", shape=[ 2, ], values=[1, 1], ) cons = Constraint( name="cons", symbol="cons", cons_type=ConstraintTypeEnum.LTE, func="b-A@X", is_linear=True, is_convex=True, is_twice_differentiable=True, ) obj = Objective( name="f_1", symbol="f_1", func="Sum(-0.5*(X**2))" if dqp else "-0.5*X@X", maximize=True, is_linear=False, is_convex=True, is_twice_differentiable=True, ) return Problem( name="Simple constrained quadratic tensor test problem.", description="A simple problem for testing purposes.", variables=[xvar], constants=[mmult, bvector], constraints=[cons], objectives=[obj], is_twice_differentiable=True, is_convex=True, ) ``` ### simple_data_problem ``` simple_data_problem() -> Problem ``` Defines a simple problem with only data-based objective functions. Source code in `desdeo/problem/testproblems/simple_problem.py` ``` def simple_data_problem() -> Problem: """Defines a simple problem with only data-based objective functions.""" constants = [Constant(name="c", symbol="c", value=1000)] n_var = 5 variables = [ Variable( name=f"y_{i}", symbol=f"y_{i}", variable_type=VariableTypeEnum.real, lowerbound=-50.0, upperbound=50.0, initial_value=0.1, ) for i in range(1, n_var + 1) ] n_objectives = 3 # only the first objective is to be maximized, the rest are to be minimized objectives = [ Objective( name=f"g_{i}", symbol=f"g_{i}", func=None, objective_type=ObjectiveTypeEnum.data_based, maximize=i == 1, ideal=3000 if i == 1 else -60.0 if i == 3 else 0, # noqa: PLR2004 nadir=0 if i == 1 else 15 - 2.0 if i == 3 else 15, # noqa: PLR2004 ) for i in range(1, n_objectives + 1) ] constraints = [Constraint(name="cons 1", symbol="c_1", cons_type=ConstraintTypeEnum.EQ, func="y_1 + y_2 - c")] data_len = 10 var_data = {f"y_{i}": [i * 0.5 + j for j in range(data_len)] for i in range(1, n_var + 1)} obj_data = { "g_1": [sum(var_data[f"y_{j}"][i] for j in range(1, n_var + 1)) ** 2 for i in range(data_len)], "g_2": [max(var_data[f"y_{j}"][i] for j in range(1, n_var + 1)) for i in range(data_len)], "g_3": [-sum(var_data[f"y_{j}"][i] for j in range(1, n_var + 1)) for i in range(data_len)], } discrete_def = DiscreteRepresentation(variable_values=var_data, objective_values=obj_data) return Problem( name="Simple data problem", description="Simple problem with all objectives being data-based. Has constraints and a constant also.", constants=constants, variables=variables, objectives=objectives, constraints=constraints, discrete_representation=discrete_def, ) ``` ### simple_integer_test_problem ``` simple_integer_test_problem() -> Problem ``` Defines a simple integer problem suitable for testing purposes. Source code in `desdeo/problem/testproblems/simple_problem.py` ``` def simple_integer_test_problem() -> Problem: """Defines a simple integer problem suitable for testing purposes.""" variables = [ Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.integer, lowerbound=0, upperbound=10, initial_value=5, ), Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.integer, lowerbound=0, upperbound=10, initial_value=5, ), Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.integer, lowerbound=0, upperbound=10, initial_value=5, ), Variable( name="x_4", symbol="x_4", variable_type=VariableTypeEnum.integer, lowerbound=0, upperbound=10, initial_value=5, ), ] constants = [Constant(name="c", symbol="c", value=4.2)] f_1 = "x_1 + x_2 + x_3" f_2 = "x_2**x_4 - x_3**x_1" f_3 = "x_1 - x_2 + x_3*x_4" f_4 = "Max(Abs(x_1 - x_2), c) + Max(x_3, x_4)" # c = 4.2 f_5 = "(-x_1) * (-x_2)" objectives = [ Objective(name="f_1", symbol="f_1", func=f_1, maximize=False), # min! Objective(name="f_2", symbol="f_2", func=f_2, maximize=True), # max! Objective(name="f_3", symbol="f_3", func=f_3, maximize=True), # max! Objective(name="f_4", symbol="f_4", func=f_4, maximize=False), # min! Objective(name="f_5", symbol="f_5", func=f_5, maximize=True), # max! ] return Problem( name="Simple integer test problem.", description="A simple problem for testing purposes.", constants=constants, variables=variables, objectives=objectives, ) ``` ### simple_knapsack ``` simple_knapsack() -> Problem ``` Defines a simple multiobjective knapsack problem. Given a set of 4 items, each with a weight and three values corresponding to different objectives, the problem is defined as follows: - Item 1: weight = 2, values = (5, 10, 15) - Item 2: weight = 3, values = (4, 7, 9) - Item 3: weight = 1, values = (3, 5, 8) - Item 4: weight = 4, values = (2, 3, 5) The problem is then to maximize the following functions: [\\begin{align\*} f_1(x) &= 5x_1 + 4x_2 + 3x_3 + 2x_4 \\ f_2(x) &= 10x_1 + 7x_2 + 5x_3 + 3x_4 \\ f_3(x) &= 15x_1 + 9x_2 + 8x_3 + 5x_4 \\ \\text{s.t.}\\quad & 2x_1 + 3x_2 + 1x_3 + 4x_4 \\leq 7 \\ & x_i \\in {0,1} \\quad \\text{for} \\quad i = 1, 2, 3, 4, \\end{align\*}] where the inequality constraint is a weight constraint. The problem is a binary variable problem. Returns: | Name | Type | Description | | --------- | --------- | ---------------------------- | | `Problem` | `Problem` | the simple knapsack problem. | Source code in `desdeo/problem/testproblems/knapsack_problem.py` ``` def simple_knapsack() -> Problem: r"""Defines a simple multiobjective knapsack problem. Given a set of 4 items, each with a weight and three values corresponding to different objectives, the problem is defined as follows: - Item 1: weight = 2, values = (5, 10, 15) - Item 2: weight = 3, values = (4, 7, 9) - Item 3: weight = 1, values = (3, 5, 8) - Item 4: weight = 4, values = (2, 3, 5) The problem is then to maximize the following functions: \begin{align*} f_1(x) &= 5x_1 + 4x_2 + 3x_3 + 2x_4 \\ f_2(x) &= 10x_1 + 7x_2 + 5x_3 + 3x_4 \\ f_3(x) &= 15x_1 + 9x_2 + 8x_3 + 5x_4 \\ \text{s.t.}\quad & 2x_1 + 3x_2 + 1x_3 + 4x_4 \leq 7 \\ & x_i \in \{0,1\} \quad \text{for} \quad i = 1, 2, 3, 4, \end{align*} where the inequality constraint is a weight constraint. The problem is a binary variable problem. Returns: Problem: the simple knapsack problem. """ variables = [ Variable( name=f"x_{i}", symbol=f"x_{i}", variable_type=VariableTypeEnum.binary, lowerbound=0, upperbound=1, initial_value=0, ) for i in range(1, 5) ] exprs = { "f1": "5*x_1 + 4*x_2 + 3*x_3 + 2*x_4", "f2": "10*x_1 + 7*x_2 + 5*x_3 + 3*x_4", "f3": "15*x_1 + 9*x_2 + 8*x_3 + 5*x_4", } ideals = {"f1": 15, "f2": 25, "f3": 37} objectives = [ Objective( name=f"f_{i}", symbol=f"f_{i}", func=exprs[f"f{i}"], maximize=True, ideal=ideals[f"f{i}"], nadir=0, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ) for i in range(1, 4) ] constraints = [ Constraint( name="Weight constraint", symbol="g_w", cons_type=ConstraintTypeEnum.LTE, func="2*x_1 + 3*x_2 + 1*x_3 + 4*x_4 - 7", is_linear=True, is_convex=True, is_twice_differentiable=True, ) ] return Problem( name="Simple knapsack", description="A simple knapsack problem with three objectives to be maximized.", variables=variables, objectives=objectives, constraints=constraints, ) ``` ### simple_knapsack_vectors ``` simple_knapsack_vectors() ``` Define a simple variant of the knapsack problem that utilizes vectors (TensorVariable and TensorConstant). Source code in `desdeo/problem/testproblems/knapsack_problem.py` ``` def simple_knapsack_vectors(): """Define a simple variant of the knapsack problem that utilizes vectors (TensorVariable and TensorConstant).""" n_items = 4 weight_values = [2, 3, 4, 5] profit_values = [3, 5, 6, 8] efficiency_values = [4, 2, 7, 3] max_weight = Constant(name="Maximum weights", symbol="w_max", value=5) weights = TensorConstant(name="Weights of the items", symbol="W", shape=[len(weight_values)], values=weight_values) profits = TensorConstant(name="Profits", symbol="P", shape=[len(profit_values)], values=profit_values) efficiencies = TensorConstant( name="Efficiencies", symbol="E", shape=[len(efficiency_values)], values=efficiency_values ) choices = TensorVariable( name="Chosen items", symbol="X", shape=[n_items], variable_type="binary", lowerbounds=n_items * [0], upperbounds=n_items * [1], initial_values=n_items * [1], ) profit_objective = Objective( name="max profit", symbol="f_1", func="P@X", maximize=True, ideal=8, nadir=0, is_linear=True, is_convex=False, is_twice_differentiable=False, ) efficiency_objective = Objective( name="max efficiency", symbol="f_2", func="E@X", maximize=True, ideal=7, nadir=0, is_linear=True, is_convex=False, is_twice_differentiable=False, ) weight_constraint = Constraint( name="Weight constraint", symbol="g_1", cons_type="<=", func="W@X - w_max", is_linear=True, is_convex=False, is_twice_differentiable=False, ) return Problem( name="Simple two-objective Knapsack problem", description="A simple variant of the classic combinatorial problem.", constants=[max_weight, weights, profits, efficiencies], variables=[choices], objectives=[profit_objective, efficiency_objective], constraints=[weight_constraint], ) ``` ### simple_linear_test_problem ``` simple_linear_test_problem() -> Problem ``` Defines a simple single objective linear problem suitable for testing purposes. Source code in `desdeo/problem/testproblems/simple_problem.py` ``` def simple_linear_test_problem() -> Problem: """Defines a simple single objective linear problem suitable for testing purposes.""" variables = [ Variable(name="x_1", symbol="x_1", variable_type="real", lowerbound=-10, upperbound=10, initial_value=5), Variable(name="x_2", symbol="x_2", variable_type="real", lowerbound=-10, upperbound=10, initial_value=5), ] constants = [Constant(name="c", symbol="c", value=4.2)] f_1 = "x_1 + x_2" objectives = [ Objective(name="f_1", symbol="f_1", func=f_1, maximize=False), # min! ] con_1 = Constraint(name="g_1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func="c - x_1") con_2 = Constraint(name="g_2", symbol="g_2", cons_type=ConstraintTypeEnum.LTE, func="0.5*x_1 - x_2") return Problem( name="Simple linear test problem.", description="A simple problem for testing purposes.", constants=constants, variables=variables, constraints=[con_1, con_2], objectives=objectives, is_linear=True, is_convex=True, is_twice_differentiable=True, ) ``` ### simple_scenario_model ``` simple_scenario_model() -> ScenarioModel ``` Returns a ScenarioModel for testing scenario-based problem construction. The base problem contains elements shared across all scenarios (f_3, con_3). The pool contains scenario-specific elements. Scenario s_1: objectives f_1, f_2 and constraints con_1, con_4. Scenario s_2: objectives f_2, f_4, f_5, constraints con_2, con_4, and extra_func extra_1. Source code in `desdeo/problem/testproblems/simple_problem.py` ``` def simple_scenario_model() -> ScenarioModel: """Returns a ScenarioModel for testing scenario-based problem construction. The base problem contains elements shared across all scenarios (f_3, con_3). The pool contains scenario-specific elements. Scenario s_1: objectives f_1, f_2 and constraints con_1, con_4. Scenario s_2: objectives f_2, f_4, f_5, constraints con_2, con_4, and extra_func extra_1. """ constants = [Constant(name="c_1", symbol="c_1", value=3)] variables = [ Variable( name="x_1", symbol="x_1", lowerbound=-5.1, upperbound=6.2, initial_value=0, variable_type=VariableTypeEnum.real, ), Variable( name="x_2", symbol="x_2", lowerbound=-5.2, upperbound=6.1, initial_value=0, variable_type=VariableTypeEnum.real, ), ] base_problem = Problem( name="Simple scenario base problem", description="Base problem for scenario testing; contains elements shared by all scenarios.", variables=variables, constants=constants, objectives=[ Objective( name="f_3", symbol="f_3", func="(x_1 - 3)**2 + x_2", maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ), ], constraints=[ Constraint( name="con_3", symbol="con_3", cons_type=ConstraintTypeEnum.LTE, func="x_2 - 50", is_linear=True, is_convex=True, is_twice_differentiable=True, ), ], ) return ScenarioModel( scenario_tree={"ROOT": ["s_1", "s_2", "s_3"], "s_1": [], "s_2": [], "s_3": []}, scenario_probabilities={"s_1": 0.2, "s_2": 0.3, "s_3": 0.5}, anticipation_stop={"ROOT": ["x_1"]}, base_problem=base_problem, objectives=[ # index 0: f_1 used by s_1 Objective( name="f_1 (s_1)", symbol="f_1", func="x_1 + x_2", maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ), # index 1: f_2 used by s_1 and s_3 Objective( name="f_2 (s_1/s_3)", symbol="f_2", func="x_1 - x_2", maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ), # index 2: f_1 used by s_2 and s_3 Objective( name="f_1 (s_2/s_3)", symbol="f_1", func="c_1 + x_2**2 - x_1", maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=True, is_twice_differentiable=True, ), # index 3: f_2 used by s_2 Objective( name="f_2 (s_2)", symbol="f_2", func="-x_1 - x_2", maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ), ], constraints=[ Constraint( name="con_1", symbol="con_1", cons_type=ConstraintTypeEnum.LTE, func="x_1 + x_2 - 15", is_linear=True, is_convex=True, is_twice_differentiable=True, ), Constraint( name="con_2", symbol="con_2", cons_type=ConstraintTypeEnum.LTE, func="x_1 + x_2 - 65", is_linear=True, is_convex=True, is_twice_differentiable=True, ), Constraint( name="con_4", symbol="con_4", cons_type=ConstraintTypeEnum.LTE, func="extra_1 - 5", is_linear=True, is_convex=True, is_twice_differentiable=True, ), ], extra_funcs=[ # index 0: used by s_2 ExtraFunction( name="extra_1 (s_2)", symbol="extra_1", func="5*x_1", is_linear=True, is_convex=True, is_twice_differentiable=True, ), # index 1: used by s_1 ExtraFunction( name="extra_1 (s_1)", symbol="extra_1", func="2*x_1", is_linear=True, is_convex=True, is_twice_differentiable=True, ), ], constants=[ Constant(name="c_1 (s_1)", symbol="c_1", value=1.0), # index 0 Constant(name="c_1 (s_2)", symbol="c_1", value=5.0), # index 1 Constant(name="c_1 (s_3)", symbol="c_1", value=10.0), # index 2 ], scenarios={ # constants: c_1→0/1/2 per scenario # objectives: f_1→0(s_1),2(s_2/s_3) | f_2→1(s_1/s_3),3(s_2) # constraints: con_1=0, con_2=1, con_4=2 | extra_funcs: extra_1→1(s_1),0(s_2) "s_1": Scenario( constants={"c_1": 0}, objectives={"f_1": 0, "f_2": 1}, constraints={"con_1": 0, "con_4": 2}, extra_funcs={"extra_1": 1}, ), "s_2": Scenario( constants={"c_1": 1}, objectives={"f_1": 2, "f_2": 3}, constraints={"con_2": 1, "con_4": 2}, extra_funcs={"extra_1": 0}, ), "s_3": Scenario( constants={"c_1": 2}, objectives={"f_1": 2, "f_2": 1}, constraints={"con_1": 0, "con_2": 1}, ), }, ) ``` ### simple_scenario_test_problem ``` simple_scenario_test_problem() ``` Returns a simple, scenario-based multiobjective optimization test problem. Source code in `desdeo/problem/testproblems/simple_problem.py` ``` def simple_scenario_test_problem(): """Returns a simple, scenario-based multiobjective optimization test problem.""" constants = [Constant(name="c_1", symbol="c_1", value=3)] variables = [ Variable( name="x_1", symbol="x_1", lowerbound=-5.1, upperbound=6.2, initial_value=0, variable_type=VariableTypeEnum.real, ), Variable( name="x_2", symbol="x_2", lowerbound=-5.2, upperbound=6.1, initial_value=0, variable_type=VariableTypeEnum.real, ), ] constraints = [ Constraint( name="con_1", symbol="con_1", cons_type=ConstraintTypeEnum.LTE, func="x_1 + x_2 - 15", is_linear=True, is_convex=True, is_twice_differentiable=True, ), Constraint( name="con_2", symbol="con_2", cons_type=ConstraintTypeEnum.LTE, func="x_1 + x_2 - 65", is_linear=True, is_convex=True, is_twice_differentiable=True, ), Constraint( name="con_3", symbol="con_3", cons_type=ConstraintTypeEnum.LTE, func="x_2 - 50", is_linear=True, is_convex=True, is_twice_differentiable=True, ), Constraint( name="con_4", symbol="con_4", cons_type=ConstraintTypeEnum.LTE, func="x_1 - 5", is_linear=True, is_convex=True, is_twice_differentiable=True, ), ] expr_1 = "x_1 + x_2" expr_2 = "x_1 - x_2" expr_3 = "(x_1 - 3)**2 + x_2" expr_4 = "c_1 + x_2**2 - x_1" expr_5 = "-x_1 - x_2" objectives = [ Objective( name="f_1", symbol="f_1", func=expr_1, maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ), Objective( name="f_2", symbol="f_2", func=expr_2, maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ), Objective( name="f_3", symbol="f_3", func=expr_3, maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ), Objective( name="f_4", symbol="f_4", func=expr_4, maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ), Objective( name="f_5", symbol="f_5", func=expr_5, maximize=False, ideal=-100, nadir=100, objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ), ] extra_funcs = [ ExtraFunction( name="extra_1", symbol="extra_1", func="5*x_1", is_linear=True, is_convex=True, is_twice_differentiable=True, ) ] return Problem( name="Simple scenario test problem", description="For testing the implementation of scenario-based problems.", variables=variables, constants=constants, constraints=constraints, objectives=objectives, extra_funcs=extra_funcs, ) ``` ### simple_test_problem ``` simple_test_problem() -> Problem ``` Defines a simple problem suitable for testing purposes. Source code in `desdeo/problem/testproblems/simple_problem.py` ``` def simple_test_problem() -> Problem: """Defines a simple problem suitable for testing purposes.""" variables = [ Variable(name="x_1", symbol="x_1", variable_type="real", lowerbound=0, upperbound=10, initial_value=5), Variable(name="x_2", symbol="x_2", variable_type="real", lowerbound=0, upperbound=10, initial_value=5), ] constants = [Constant(name="c", symbol="c", value=4.2)] f_1 = "x_1 + x_2" f_2 = "x_2**3" f_3 = "x_1 + x_2" f_4 = "Max(Abs(x_1 - x_2), c)" # c = 4.2 f_5 = "(-x_1) * (-x_2)" objectives = [ Objective(name="f_1", symbol="f_1", func=f_1, maximize=False), # min! Objective(name="f_2", symbol="f_2", func=f_2, maximize=True), # max! Objective(name="f_3", symbol="f_3", func=f_3, maximize=True), # max! Objective(name="f_4", symbol="f_4", func=f_4, maximize=False), # min! Objective(name="f_5", symbol="f_5", func=f_5, maximize=True), # max! ] return Problem( name="Simple test problem.", description="A simple problem for testing purposes.", constants=constants, variables=variables, objectives=objectives, ) ``` ### spanish_sustainability_problem_discrete ``` spanish_sustainability_problem_discrete() ``` Implements the Spanish sustainability problem using Pareto front representation. Source code in `desdeo/problem/testproblems/spanish_sustainability_problem.py` ``` def spanish_sustainability_problem_discrete(): """Implements the Spanish sustainability problem using Pareto front representation.""" filename = "datasets/sustainability_spanish.csv" varnames = [f"x{i}" for i in range(1, 12)] objnames = {"f1": "social", "f2": "economic", "f3": "environmental"} path = Path(__file__).parent.parent.parent.parent / filename data = pl.read_csv(path, has_header=True) data = data.rename({"social": "f1", "economic": "f2", "environmental": "f3"}) variables = [ Variable( name=varname, symbol=varname, variable_type=VariableTypeEnum.real, lowerbound=data[varname].min(), upperbound=data[varname].max(), initial_value=data[varname].mean(), ) for varname in varnames ] objectives = [ Objective( name=objnames[objname], symbol=objname, objective_type=ObjectiveTypeEnum.data_based, ideal=data[objname].max(), nadir=data[objname].min(), maximize=True, ) for objname in objnames ] discrete_def = DiscreteRepresentation( variable_values=data[varnames].to_dict(), objective_values=data[[obj.symbol for obj in objectives]].to_dict(), ) return Problem( name="Spanish sustainability problem (Discrete)", description="Defines a sustainability problem with three indicators: social, ecological, and environmental.", variables=variables, objectives=objectives, discrete_representation=discrete_def, ) ``` ### summer_cabin_battery_problem ``` summer_cabin_battery_problem( initial_soc: float = 0.0, n_panels_max: int = 50 ) -> Problem ``` Build a bi-objective MILP for battery + solar investment and scheduling at the summer cabin. Decision variables: - y ∈ {0,1}: whether the battery is installed - E ∈ [0, 42] kWh: battery capacity (14-42 kWh if installed, 0 otherwise) - n ∈ {0,...,n_panels_max}: number of 160 W solar panels - c_t ∈ [0, 10] kW: hourly charging power (vector of length T) - d_t ∈ [0, 10] kW: hourly discharging power (vector of length T) - soc_t ∈ [0, 42] kWh: state of charge (vector of length T) - buy_t ≥ 0 kWh/h: electricity purchased from the grid (vector of length T) - sell_t ≥ 0 kWh/h: electricity sold to the grid (vector of length T) Objectives: - f_1: total electricity cost (EUR) = Σ q_t·buy_t - Σ p_t·sell_t where q = p + 0.05 EUR/kWh (spot + transmission) for buying, and p is the spot price for selling (no transmission). - f_2: total investment cost (EUR) = 2000·y + 310·E + 200·n Parameters: | Name | Type | Description | Default | | -------------- | ------- | -------------------------------------------------------- | ------- | | `initial_soc` | `float` | initial state of charge in kWh. Defaults to 0.0 (empty). | `0.0` | | `n_panels_max` | `int` | upper bound on number of solar panels. Defaults to 50. | `50` | Returns: | Type | Description | | --------- | -------------------------- | | `Problem` | A DESDEO Problem instance. | Source code in `desdeo/problem/testproblems/summer_cabin_electricity.py` ``` def summer_cabin_battery_problem(initial_soc: float = 0.0, n_panels_max: int = 50) -> "Problem": """Build a bi-objective MILP for battery + solar investment and scheduling at the summer cabin. Decision variables: - y ∈ {0,1}: whether the battery is installed - E ∈ [0, 42] kWh: battery capacity (14-42 kWh if installed, 0 otherwise) - n ∈ {0,...,n_panels_max}: number of 160 W solar panels - c_t ∈ [0, 10] kW: hourly charging power (vector of length T) - d_t ∈ [0, 10] kW: hourly discharging power (vector of length T) - soc_t ∈ [0, 42] kWh: state of charge (vector of length T) - buy_t ≥ 0 kWh/h: electricity purchased from the grid (vector of length T) - sell_t ≥ 0 kWh/h: electricity sold to the grid (vector of length T) Objectives: - f_1: total electricity cost (EUR) = Σ q_t·buy_t - Σ p_t·sell_t where q = p + 0.05 EUR/kWh (spot + transmission) for buying, and p is the spot price for selling (no transmission). - f_2: total investment cost (EUR) = 2000·y + 310·E + 200·n Args: initial_soc: initial state of charge in kWh. Defaults to 0.0 (empty). n_panels_max: upper bound on number of solar panels. Defaults to 50. Returns: A DESDEO Problem instance. """ df = generate_summer_cabin_electricity_data() prices = df["price_EUR_kWh"].to_numpy() loads = df["load_kWh"].to_numpy() solar = generate_solar_profile() T = len(prices) # --- Variables --- installed = Variable( name="Battery installed", symbol="y", variable_type=VariableTypeEnum.binary, lowerbound=0, upperbound=1, initial_value=0, ) capacity = Variable( name="Battery capacity (kWh)", symbol="E", variable_type=VariableTypeEnum.real, lowerbound=0.0, upperbound=42.0, initial_value=0.0, ) n_panels = Variable( name="Number of solar panels", symbol="n", variable_type=VariableTypeEnum.integer, lowerbound=0, upperbound=n_panels_max, initial_value=0, ) charge = TensorVariable( name="Charging power (kW)", symbol="c", shape=[T], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=10.0, initial_values=0.0, ) discharge = TensorVariable( name="Discharging power (kW)", symbol="d", shape=[T], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=10.0, initial_values=0.0, ) soc = TensorVariable( name="State of charge (kWh)", symbol="soc", shape=[T], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=42.0, initial_values=initial_soc, ) buy = TensorVariable( name="Grid electricity purchased (kWh/h)", symbol="buy", shape=[T], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=None, initial_values=0.0, ) sell = TensorVariable( name="Grid electricity sold (kWh/h)", symbol="sell", shape=[T], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=None, initial_values=0.0, ) # --- Constants --- price_const = TensorConstant( name="Electricity spot price (EUR/kWh)", symbol="p", shape=[T], values=prices.tolist(), ) load_const = TensorConstant( name="Electricity load (kWh/h)", symbol="l", shape=[T], values=loads.tolist(), ) solar_const = TensorConstant( name="Solar production per panel (kWh/h per panel)", symbol="sol", shape=[T], values=solar.tolist(), ) # --- Constraints --- constraints = [ # Battery capacity links: E = 0 if y = 0; E in [14, 42] if y = 1 Constraint( name="Capacity zero if not installed", symbol="cap_ub_con", func=["Add", "E", ["Negate", ["Multiply", 42.0, "y"]]], cons_type=ConstraintTypeEnum.LTE, is_linear=True, is_convex=True, is_twice_differentiable=True, ), Constraint( name="Minimum capacity if installed", symbol="cap_lb_con", func=["Add", ["Multiply", 14.0, "y"], ["Negate", "E"]], cons_type=ConstraintTypeEnum.LTE, is_linear=True, is_convex=True, is_twice_differentiable=True, ), # SOC dynamics: soc_1 = initial_soc + c_1 - d_1 Constraint( name="SOC dynamics t=1", symbol="soc_con_1", func=["Add", ["At", "soc", 1], -initial_soc, ["Negate", ["At", "c", 1]], ["At", "d", 1]], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ), # SOC dynamics t=2..T as a single vector constraint Constraint( name="SOC dynamics t=2..T", symbol="soc_con", func=[ "Add", ["Extract", "soc", ["Tuple", 2, T]], ["Negate", ["Extract", "soc", ["Tuple", 1, T - 1]]], ["Negate", ["Extract", "c", ["Tuple", 2, T]]], ["Extract", "d", ["Tuple", 2, T]], ], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ), # soc <= E (vector) Constraint( name="SOC capacity upper bound", symbol="soc_cap_con", func=["Subtract", "soc", "E"], cons_type=ConstraintTypeEnum.LTE, is_linear=True, is_convex=True, is_twice_differentiable=True, ), # Energy balance: buy - sell + d - c + n*sol = l (vector) Constraint( name="Energy balance", symbol="energy_bal", func=["Add", "buy", ["Negate", "sell"], "d", ["Negate", "c"], ["Multiply", "n", "sol"], ["Negate", "l"]], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ), ] return Problem( name="Summer cabin battery and solar investment optimization", description=( "Jointly optimize battery and solar panel investment with hourly scheduling over a summer season. " "Battery: 2000 EUR fixed + 310 EUR/kWh, 10 kW rate. Solar: 200 EUR per 160 W panel. " "Buying price includes 0.05 EUR/kWh transmission; selling uses spot price only." ), variables=[installed, capacity, n_panels, charge, discharge, soc, buy, sell], constants=[price_const, load_const, solar_const], objectives=[ Objective( name="Electricity cost", description="Total electricity cost", symbol="f_1", func=[ "Add", ["MatMul", "p", "buy"], ["Multiply", 0.05, ["Sum", "buy"]], ["Negate", ["MatMul", "p", "sell"]], ], unit="EUR", maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ), Objective( name="Investment cost", description="Total investment cost", symbol="f_2", func=["Add", ["Multiply", 2000.0, "y"], ["Multiply", 310.0, "E"], ["Multiply", 200.0, "n"]], unit="EUR", maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ), ], constraints=constraints, ) ``` ### summer_cabin_battery_problem_split ``` summer_cabin_battery_problem_split( initial_soc: float = 0.0, n_panels_max: int = 50 ) -> Problem ``` Same problem as summer_cabin_battery_problem but the time horizon is split into 3 equal segments. Each segment has its own TensorVariables and TensorConstants. SOC continuity across segment boundaries is enforced by an equality constraint that reads the last element of the previous segment's SOC variable via the At operator. Objective values are identical to the monolithic form. Parameters: | Name | Type | Description | Default | | -------------- | ------- | -------------------------------------------------------- | ------- | | `initial_soc` | `float` | initial state of charge in kWh. Defaults to 0.0 (empty). | `0.0` | | `n_panels_max` | `int` | upper bound on number of solar panels. Defaults to 50. | `50` | Returns: | Type | Description | | --------- | -------------------------- | | `Problem` | A DESDEO Problem instance. | Source code in `desdeo/problem/testproblems/summer_cabin_electricity.py` ``` def summer_cabin_battery_problem_split(initial_soc: float = 0.0, n_panels_max: int = 50) -> "Problem": """Same problem as summer_cabin_battery_problem but the time horizon is split into 3 equal segments. Each segment has its own TensorVariables and TensorConstants. SOC continuity across segment boundaries is enforced by an equality constraint that reads the last element of the previous segment's SOC variable via the At operator. Objective values are identical to the monolithic form. Args: initial_soc: initial state of charge in kWh. Defaults to 0.0 (empty). n_panels_max: upper bound on number of solar panels. Defaults to 50. Returns: A DESDEO Problem instance. """ df = generate_summer_cabin_electricity_data() prices = df["price_EUR_kWh"].to_numpy() loads = df["load_kWh"].to_numpy() solar = generate_solar_profile() T = len(prices) N_SEG = 3 S = T // N_SEG # 736 hours per segment # --- Shared scalar investment variables --- installed = Variable( name="Battery installed", symbol="y", variable_type=VariableTypeEnum.binary, lowerbound=0, upperbound=1, initial_value=0, ) capacity = Variable( name="Battery capacity (kWh)", symbol="E", variable_type=VariableTypeEnum.real, lowerbound=0.0, upperbound=42.0, initial_value=0.0, ) n_panels = Variable( name="Number of solar panels", symbol="n", variable_type=VariableTypeEnum.integer, lowerbound=0, upperbound=n_panels_max, initial_value=0, ) # --- Per-segment variables and constants --- seg_vars = [] # seg_vars[k-1] = [charge_k, discharge_k, soc_k, buy_k, sell_k] seg_consts = [] # seg_consts[k-1] = [price_k, load_k, solar_k] for k in range(1, N_SEG + 1): sl = slice((k - 1) * S, k * S) seg_vars.append( [ TensorVariable( name=f"Charging power segment {k} (kW)", symbol=f"c_s{k}", shape=[S], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=10.0, initial_values=0.0, ), TensorVariable( name=f"Discharging power segment {k} (kW)", symbol=f"d_s{k}", shape=[S], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=10.0, initial_values=0.0, ), TensorVariable( name=f"State of charge segment {k} (kWh)", symbol=f"soc_s{k}", shape=[S], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=42.0, initial_values=initial_soc, ), TensorVariable( name=f"Grid purchased segment {k} (kWh/h)", symbol=f"buy_s{k}", shape=[S], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=None, initial_values=0.0, ), TensorVariable( name=f"Grid sold segment {k} (kWh/h)", symbol=f"sell_s{k}", shape=[S], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=None, initial_values=0.0, ), ] ) seg_consts.append( [ TensorConstant( name=f"Spot price segment {k} (EUR/kWh)", symbol=f"p_s{k}", shape=[S], values=prices[sl].tolist(), ), TensorConstant( name=f"Load segment {k} (kWh/h)", symbol=f"l_s{k}", shape=[S], values=loads[sl].tolist(), ), TensorConstant( name=f"Solar per panel segment {k} (kWh/h)", symbol=f"sol_s{k}", shape=[S], values=solar[sl].tolist(), ), ] ) # --- Constraints --- constraints = [ Constraint( name="Capacity zero if not installed", symbol="cap_ub_con", func=["Add", "E", ["Negate", ["Multiply", 42.0, "y"]]], cons_type=ConstraintTypeEnum.LTE, is_linear=True, is_convex=True, is_twice_differentiable=True, ), Constraint( name="Minimum capacity if installed", symbol="cap_lb_con", func=["Add", ["Multiply", 14.0, "y"], ["Negate", "E"]], cons_type=ConstraintTypeEnum.LTE, is_linear=True, is_convex=True, is_twice_differentiable=True, ), ] for k in range(1, N_SEG + 1): c_sym = f"c_s{k}" d_sym = f"d_s{k}" soc_sym = f"soc_s{k}" buy_sym = f"buy_s{k}" sell_sym = f"sell_s{k}" sol_sym = f"sol_s{k}" l_sym = f"l_s{k}" # SOC at t=1: reference initial_soc for segment 1, or last element of previous segment prev_soc_term = -initial_soc if k == 1 else ["Negate", ["At", f"soc_s{k - 1}", S]] constraints.append( Constraint( name=f"SOC dynamics segment {k} t=1", symbol=f"soc_con_s{k}_1", func=["Add", ["At", soc_sym, 1], prev_soc_term, ["Negate", ["At", c_sym, 1]], ["At", d_sym, 1]], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ) ) constraints.append( Constraint( name=f"SOC dynamics segment {k} t=2..{S}", symbol=f"soc_con_s{k}", func=[ "Add", ["Extract", soc_sym, ["Tuple", 2, S]], ["Negate", ["Extract", soc_sym, ["Tuple", 1, S - 1]]], ["Negate", ["Extract", c_sym, ["Tuple", 2, S]]], ["Extract", d_sym, ["Tuple", 2, S]], ], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ) ) constraints.append( Constraint( name=f"SOC capacity upper bound segment {k}", symbol=f"soc_cap_con_s{k}", func=["Subtract", soc_sym, "E"], cons_type=ConstraintTypeEnum.LTE, is_linear=True, is_convex=True, is_twice_differentiable=True, ) ) constraints.append( Constraint( name=f"Energy balance segment {k}", symbol=f"energy_bal_s{k}", func=[ "Add", buy_sym, ["Negate", sell_sym], d_sym, ["Negate", c_sym], ["Multiply", "n", sol_sym], ["Negate", l_sym], ], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ) ) # f_1 = sum over all segments of (p_sk · buy_sk + 0.05*sum(buy_sk) - p_sk · sell_sk) f1_terms = [] for k in range(1, N_SEG + 1): f1_terms += [ ["MatMul", f"p_s{k}", f"buy_s{k}"], ["Multiply", 0.05, ["Sum", f"buy_s{k}"]], ["Negate", ["MatMul", f"p_s{k}", f"sell_s{k}"]], ] all_variables = [installed, capacity, n_panels] all_constants = [] for k in range(N_SEG): all_variables.extend(seg_vars[k]) all_constants.extend(seg_consts[k]) return Problem( name="Summer cabin battery and solar investment optimization (split)", description=( "Same as summer_cabin_battery_problem but the time horizon is split into 3 segments " "to reduce per-block tensor sizes while preserving solution equivalence." ), variables=all_variables, constants=all_constants, objectives=[ Objective( name="Electricity cost", description="Total electricity cost", symbol="f_1", func=["Add", *f1_terms], unit="EUR", maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ), Objective( name="Investment cost", description="Total investment cost", symbol="f_2", func=["Add", ["Multiply", 2000.0, "y"], ["Multiply", 310.0, "E"], ["Multiply", 200.0, "n"]], unit="EUR", maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ), ], constraints=constraints, ) ``` ### summer_cabin_battery_problem_split_scenario ``` summer_cabin_battery_problem_split_scenario( initial_soc: float = 0.0, n_panels_max: int = 50 ) -> ScenarioModel ``` Build a ScenarioModel for the split summer cabin battery problem with two-level outage scenarios. Scenario tree (4 leaf scenarios): ROOT → [S1, S2] — at the start of segment 2, S2 has a 4-hour grid outage S1 → [S1a, S1b] — at the start of segment 3, S1b has a 4-hour grid outage S2 → [S2a, S2b] — at the start of segment 3, S2b has a 4-hour grid outage During an outage, grid buy and sell are forced to zero. An unmet-demand slack variable absorbs any energy balance gap; a binary indicator records whether the hour went unserved. Unmet-demand variables and the f_3 objective are only added to scenarios where an outage can actually occur, keeping each scenario problem as small as possible: S1a — no outage, no extra variables, no f_3 S1b — s3 outage: 8 extra vars, f_3 = Sum(z_s3) S2a — s2 outage: 8 extra vars, f_3 = Sum(z_s2) S2b — both: 16 extra vars, f_3 = Sum(z_s2 + z_s3) The base problem is the unmodified split problem. All additions live entirely in the ScenarioModel pool. Non-anticipativity ROOT: investment variables (y, E, n) and all segment-1 schedule variables. S1/S2: segment-2 schedule variables within each branch. Parameters: | Name | Type | Description | Default | | -------------- | ------- | -------------------------------------- | ------- | | `initial_soc` | `float` | initial state of charge in kWh. | `0.0` | | `n_panels_max` | `int` | upper bound on number of solar panels. | `50` | Returns: | Type | Description | | --------------- | ------------------------- | | `ScenarioModel` | A ScenarioModel instance. | Source code in `desdeo/problem/testproblems/summer_cabin_electricity.py` ``` def summer_cabin_battery_problem_split_scenario( initial_soc: float = 0.0, n_panels_max: int = 50, ) -> ScenarioModel: """Build a ScenarioModel for the split summer cabin battery problem with two-level outage scenarios. Scenario tree (4 leaf scenarios): ROOT → [S1, S2] — at the start of segment 2, S2 has a 4-hour grid outage S1 → [S1a, S1b] — at the start of segment 3, S1b has a 4-hour grid outage S2 → [S2a, S2b] — at the start of segment 3, S2b has a 4-hour grid outage During an outage, grid buy and sell are forced to zero. An unmet-demand slack variable absorbs any energy balance gap; a binary indicator records whether the hour went unserved. Unmet-demand variables and the f_3 objective are only added to scenarios where an outage can actually occur, keeping each scenario problem as small as possible: S1a — no outage, no extra variables, no f_3 S1b — s3 outage: 8 extra vars, f_3 = Sum(z_s3) S2a — s2 outage: 8 extra vars, f_3 = Sum(z_s2) S2b — both: 16 extra vars, f_3 = Sum(z_s2 + z_s3) The base problem is the unmodified split problem. All additions live entirely in the ScenarioModel pool. Non-anticipativity: ROOT: investment variables (y, E, n) and all segment-1 schedule variables. S1/S2: segment-2 schedule variables within each branch. Args: initial_soc: initial state of charge in kWh. n_panels_max: upper bound on number of solar panels. Returns: A ScenarioModel instance. """ base = summer_cabin_battery_problem_split(initial_soc=initial_soc, n_panels_max=n_panels_max) H = _N_OUTAGE_HRS var_pool: list[Variable] = [] var_idx: dict[str, int] = {} for k in (2, 3): v = TensorVariable( name=f"Unmet demand s{k} (kWh)", symbol=f"unmet_s{k}", shape=[H], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=None, initial_values=0.0, ) var_idx[v.symbol] = len(var_pool) var_pool.append(v) for k in (2, 3): v = TensorVariable( name=f"Demand unserved indicator s{k}", symbol=f"z_s{k}", shape=[H], variable_type=VariableTypeEnum.binary, lowerbounds=0, upperbounds=1, initial_values=0, ) var_idx[v.symbol] = len(var_pool) var_pool.append(v) def _f3(segments: tuple[int, ...]) -> Objective: z_terms = [["Sum", f"z_s{k}"] for k in segments] return Objective( name="Power outage", description="Hours with unserved electricity demand", symbol="f_3", func=z_terms[0] if len(z_terms) == 1 else ["Add", *z_terms], unit="h", maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ) obj_pool: list[Objective] = [] obj_idx: dict[str, int] = {} # scenario name → pool index for scenario_name, segs in [("S2a", (2,)), ("S1b", (3,)), ("S2b", (2, 3))]: obj_idx[scenario_name] = len(obj_pool) obj_pool.append(_f3(segs)) obj_idx["S1a"] = len(obj_pool) obj_pool.append( Objective( name="Power outage", description="Hours with unserved electricity demand", symbol="f_3", func=["Multiply", 0, "y"], # always 0 — no outage possible in this scenario unit="h", maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ) ) con_pool: list[Constraint] = [] con_idx: dict[str, int] = {} for k in (2, 3): c = Constraint( name=f"Energy balance s{k} t={H}+1.. (no unmet slack)", symbol=f"energy_bal_s{k}", func=[ "Add", ["Exclude", f"buy_s{k}", ["Tuple", 1, H]], ["Negate", ["Exclude", f"sell_s{k}", ["Tuple", 1, H]]], ["Exclude", f"d_s{k}", ["Tuple", 1, H]], ["Negate", ["Exclude", f"c_s{k}", ["Tuple", 1, H]]], ["Multiply", "n", ["Exclude", f"sol_s{k}", ["Tuple", 1, H]]], ["Negate", ["Exclude", f"l_s{k}", ["Tuple", 1, H]]], ], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_idx[c.symbol] = len(con_pool) con_pool.append(c) c = Constraint( name=f"Energy balance s{k} t=1..{H} (with unmet slack)", symbol=f"energy_bal_out_s{k}", func=[ "Add", ["Extract", f"d_s{k}", ["Tuple", 1, H]], ["Negate", ["Extract", f"c_s{k}", ["Tuple", 1, H]]], ["Multiply", "n", ["Extract", f"sol_s{k}", ["Tuple", 1, H]]], f"unmet_s{k}", ["Negate", ["Extract", f"l_s{k}", ["Tuple", 1, H]]], ], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_idx[c.symbol] = len(con_pool) con_pool.append(c) for k in (2, 3): c = Constraint( name=f"Big-M unmet indicator s{k} t=1..{H}", symbol=f"bigm_s{k}", func=["Subtract", f"unmet_s{k}", ["Multiply", _M_UNMET, f"z_s{k}"]], cons_type=ConstraintTypeEnum.LTE, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_idx[c.symbol] = len(con_pool) con_pool.append(c) for k in (2, 3): c = Constraint( name=f"Outage no-trade s{k} t=1..{H}", symbol=f"outage_trade_s{k}", func=["Add", ["Extract", f"buy_s{k}", ["Tuple", 1, H]], ["Extract", f"sell_s{k}", ["Tuple", 1, H]]], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_idx[c.symbol] = len(con_pool) con_pool.append(c) _outage_segs: dict[str, tuple[int, ...]] = {"S1a": (), "S2a": (2,), "S1b": (3,), "S2b": (2, 3)} scenarios: dict[str, Scenario] = {} for name, segs in _outage_segs.items(): variables: dict[str, int] = {} constraints: dict[str, int] = {} for k in segs: variables[f"unmet_s{k}"] = var_idx[f"unmet_s{k}"] variables[f"z_s{k}"] = var_idx[f"z_s{k}"] constraints[f"energy_bal_s{k}"] = con_idx[f"energy_bal_s{k}"] constraints[f"energy_bal_out_s{k}"] = con_idx[f"energy_bal_out_s{k}"] constraints[f"bigm_s{k}"] = con_idx[f"bigm_s{k}"] constraints[f"outage_trade_s{k}"] = con_idx[f"outage_trade_s{k}"] scenarios[name] = Scenario( variables=variables, objectives={"f_3": obj_idx[name]}, constraints=constraints, ) investments = ["y", "E", "n"] s1_sched = ["c_s1", "d_s1", "soc_s1", "buy_s1", "sell_s1"] s2_sched = ["c_s2", "d_s2", "soc_s2", "buy_s2", "sell_s2"] s2_unmet = ["unmet_s2", "z_s2"] return ScenarioModel( scenario_tree={ "ROOT": ["S1", "S2"], "S1": ["S1a", "S1b"], "S2": ["S2a", "S2b"], }, scenario_probabilities={ "S1": 0.9, "S2": 0.1, "S1a": 0.81, "S1b": 0.09, "S2a": 0.09, "S2b": 0.01, }, base_problem=base, variables=tuple(var_pool), objectives=tuple(obj_pool), constraints=tuple(con_pool), scenarios=scenarios, anticipation_stop={ "ROOT": [*investments, *s1_sched], "S1": s2_sched, "S2": [*s2_sched, *s2_unmet], }, ) ``` ### summer_cabin_battery_robust_ev_problem ``` summer_cabin_battery_robust_ev_problem( initial_soc: float = 0.0, n_panels_max: int = 50 ) -> Problem ``` Build a robust multi-objective problem from the split summer cabin battery scenario model. Wraps `summer_cabin_battery_problem_split_scenario` (4-leaf outage scenario tree) and adds both worst-case robust and expected-value scalarization objectives for f_1 (electricity cost), f_2 (investment cost), and f_3 (unmet demand). Ideal and nadir bounds are computed via the payoff table method so that scalarization functions can be properly scaled. Parameters: | Name | Type | Description | Default | | -------------- | ------- | -------------------------------------- | ------- | | `initial_soc` | `float` | initial state of charge in kWh. | `0.0` | | `n_panels_max` | `int` | upper bound on number of solar panels. | `50` | Returns: | Type | Description | | --------- | --------------------------------------------------------- | | `Problem` | Combined scenario problem with ideal and nadir populated. | Source code in `desdeo/problem/testproblems/summer_cabin_electricity.py` ``` def summer_cabin_battery_robust_ev_problem(initial_soc: float = 0.0, n_panels_max: int = 50) -> Problem: """Build a robust multi-objective problem from the split summer cabin battery scenario model. Wraps `summer_cabin_battery_problem_split_scenario` (4-leaf outage scenario tree) and adds both worst-case robust and expected-value scalarization objectives for f_1 (electricity cost), f_2 (investment cost), and f_3 (unmet demand). Ideal and nadir bounds are computed via the payoff table method so that scalarization functions can be properly scaled. Args: initial_soc: initial state of charge in kWh. n_panels_max: upper bound on number of solar panels. Returns: Combined scenario problem with ideal and nadir populated. """ scenario_model = summer_cabin_battery_problem_split_scenario(initial_soc=initial_soc, n_panels_max=n_panels_max) combined_problem, symbol_maps = build_combined_scenario_problem(scenario_model) combined_problem, _ = add_worst_case_robust( scenario_model=scenario_model, symbols=["f_1", "f_2", "f_3"], combined=combined_problem, symbol_maps=symbol_maps, ) combined_problem, _ = add_expected_value( scenario_model=scenario_model, symbols=["f_1", "f_2", "f_3"], combined=combined_problem, symbol_maps=symbol_maps, ) ideal, nadir1 = payoff_table_method(combined_problem, CVXPYSolver) # payoff table does not find the actual nadir, so we need some trickery helper = combined_problem.add_constraints( [ Constraint( name="helper", symbol="help", cons_type=ConstraintTypeEnum.LTE, func=["Subtract", "E_f_3", 0.75], is_linear=True, is_convex=True, is_twice_differentiable=True, ) ] ) _, nadir2 = payoff_table_method(helper, CVXPYSolver) nadir = {key: max(nadir1[key], nadir2[key]) for key in ideal} return combined_problem.update_ideal_and_nadir(ideal, nadir) ``` ### vehicle_crashworthiness ``` vehicle_crashworthiness() -> Problem ``` Defines the vehicle crash worthiness design problem. Five decision variables describing the thickness of reinforced members (in mm) drive three minimized objectives: the frontal mass of the vehicle (kg), the collision acceleration experienced by passengers (m/s^2), and the toe board intrusion in the offset frontal crash (mm). Each (x_i) is bounded in ([1, 3]). The objective functions are the polynomial surrogate models from Liao et al. 2008. References Liao, X., Li, Q., Yang, X., Zhang, W. & Li, W. (2007). Multiobjective optimization for crash safety design of vehicles using stepwise regression model. Structural and Multidisciplinary Optimization, 35(6), 561-569. https://doi.org/10.1007/s00158-007-0163-x Returns: | Name | Type | Description | | --------- | --------- | ---------------------------------------------------- | | `Problem` | `Problem` | an instance of the vehicle crash worthiness problem. | Source code in `desdeo/problem/testproblems/vehicle_crashworthiness_problem.py` ``` def vehicle_crashworthiness() -> Problem: r"""Defines the vehicle crash worthiness design problem. Five decision variables describing the thickness of reinforced members (in mm) drive three minimized objectives: the frontal mass of the vehicle (kg), the collision acceleration experienced by passengers (m/s^2), and the toe board intrusion in the offset frontal crash (mm). Each $x_i$ is bounded in $[1, 3]$. The objective functions are the polynomial surrogate models from Liao et al. 2008. References: Liao, X., Li, Q., Yang, X., Zhang, W. & Li, W. (2007). Multiobjective optimization for crash safety design of vehicles using stepwise regression model. Structural and Multidisciplinary Optimization, 35(6), 561-569. https://doi.org/10.1007/s00158-007-0163-x Returns: Problem: an instance of the vehicle crash worthiness problem. """ variables = [ Variable( name=f"x_{i}", symbol=f"x_{i}", variable_type=VariableTypeEnum.real, lowerbound=1.0, upperbound=3.0, initial_value=2.0, ) for i in range(1, 6) ] f_1_expr = "1640.2823 + 2.3573285 * x_1 + 2.3220035 * x_2 + 4.5688768 * x_3 + 7.7213633 * x_4 + 4.4559504 * x_5" f_2_expr = ( "6.5856" " + 1.15 * x_1" " - 1.0427 * x_2" " + 0.9738 * x_3" " + 0.8364 * x_4" " - 0.3695 * x_1 * x_4" " + 0.0861 * x_1 * x_5" " + 0.3628 * x_2 * x_4" " - 0.1106 * x_1**2" " - 0.3437 * x_3**2" " + 0.1764 * x_4**2" ) f_3_expr = ( "-0.0551" " + 0.0181 * x_1" " + 0.1024 * x_2" " + 0.0421 * x_3" " - 0.0073 * x_1 * x_2" " + 0.024 * x_2 * x_3" " - 0.0118 * x_2 * x_4" " - 0.0204 * x_3 * x_4" " - 0.008 * x_3 * x_5" " - 0.0241 * x_2**2" " + 0.0109 * x_4**2" ) f_1 = Objective( name="f_1", symbol="f_1", func=f_1_expr, objective_type=ObjectiveTypeEnum.analytical, maximize=False, ideal=1600.0, nadir=1700.0, is_linear=True, is_convex=True, is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func=f_2_expr, objective_type=ObjectiveTypeEnum.analytical, maximize=False, ideal=6.0, nadir=12.0, is_linear=False, is_convex=False, is_twice_differentiable=True, ) f_3 = Objective( name="f_3", symbol="f_3", func=f_3_expr, objective_type=ObjectiveTypeEnum.analytical, maximize=False, ideal=0.038, nadir=0.30, is_linear=False, is_convex=False, is_twice_differentiable=True, ) return Problem( name="vehicle_crashworthiness", description="The vehicle crash worthiness design problem (Liao et al. 2008).", variables=variables, objectives=[f_1, f_2, f_3], ) ``` ### water_management ``` water_management(six_obj=False) -> Problem ``` Water resource planning problem. The constraints and objective functions for the water management problem are defined as follows: [\\begin{align} \\min\\quad f_1(\\mathbf{x}) &= 106780.37(x_2 + x_3) + 61704.67 \\ \\min\\quad f_2(\\mathbf{x}) &= 3000x_1 \\ \\min\\quad f_3(\\mathbf{x}) &= \\frac{305700 \\cdot 2289 x_2} {(0.06 \\cdot 2289)^{0.65}} \\ \\min\\quad f_4(\\mathbf{x}) &= 250 \\cdot 2289 \\cdot \\exp(-39.75x_2 + 9.9x_3 + 2.74) \\ \\min\\quad f_5(\\mathbf{x}) &= 25\\left( \\frac{1.39}{x_1x_2} + 4940x_3 - 80 \\right) \\ g_1(\\mathbf{x}) &= \\frac{0.00139}{x_1 x_2} + 4.94x_3 - 0.08 \\leq 1.00 \\ g_2(\\mathbf{x}) &= \\frac{0.000306}{x_1 x_2} + 1.082x_3 - 0.0986 \\leq 1.00 \\ g_3(\\mathbf{x}) &= \\frac{12.307}{x_1 x_2} + 49408.24x_3 + 4051.02 \\leq 50000.00 \\ g_4(\\mathbf{x}) &= \\frac{2.098}{x_1 x_2} + 8046.33x_3 - 696.71 \\leq 16000.00 \\ g_5(\\mathbf{x}) &= \\frac{2.138}{x_1 x_2} + 7883.39x_3 - 705.04 \\leq 10000.00 \\ g_6(\\mathbf{x}) &= \\frac{0.417}{x_1 x_2} + 1721.26x_3 - 136.54 \\leq 2000.00 \\ g_7(\\mathbf{x}) &= \\frac{0.164}{x_1 x_2} + 631.13x_3 - 54.48 \\leq 550.00 \\ \\mathbf{x}^{L} &\\leq \\mathbf{x} \\leq \\mathbf{x}^{U}, \\end{align}] where the lower and upper bounds on the variables are [ \\mathbf{x}^{L} = (0.01,,0.01,,0.01), \\qquad \\mathbf{x}^{U} = (0.45,,0.10,,0.10). ] Parameters: | Name | Type | Description | Default | | --------- | ------ | ----------------------------------------------------------------------------------------------------------------------------- | ------- | | `six_obj` | `bool` | If False, use the original 5 objectives. If true, use the sum of contraint violations as the 6th objective. Default is False. | `False` | References Ray, T., Tai, K., & Seow, K. C. (2001). Multiobjective design optimization by an evolutionary algorithm. Engineering Optimization, 33(4), 399-424. (Section 4.4.) Returns: | Name | Type | Description | | --------- | --------- | -------------------------------------------- | | `Problem` | `Problem` | an instance of the water management problem. | Source code in `desdeo/problem/testproblems/water_management_problem.py` ``` def water_management(six_obj=False) -> Problem: r"""Water resource planning problem. The constraints and objective functions for the water management problem are defined as follows: \begin{align} \min\quad f_1(\mathbf{x}) &= 106780.37(x_2 + x_3) + 61704.67 \\ \min\quad f_2(\mathbf{x}) &= 3000x_1 \\ \min\quad f_3(\mathbf{x}) &= \frac{305700 \cdot 2289 x_2} {(0.06 \cdot 2289)^{0.65}} \\ \min\quad f_4(\mathbf{x}) &= 250 \cdot 2289 \cdot \exp(-39.75x_2 + 9.9x_3 + 2.74) \\ \min\quad f_5(\mathbf{x}) &= 25\left( \frac{1.39}{x_1x_2} + 4940x_3 - 80 \right) \\ g_1(\mathbf{x}) &= \frac{0.00139}{x_1 x_2} + 4.94x_3 - 0.08 \leq 1.00 \\ g_2(\mathbf{x}) &= \frac{0.000306}{x_1 x_2} + 1.082x_3 - 0.0986 \leq 1.00 \\ g_3(\mathbf{x}) &= \frac{12.307}{x_1 x_2} + 49408.24x_3 + 4051.02 \leq 50000.00 \\ g_4(\mathbf{x}) &= \frac{2.098}{x_1 x_2} + 8046.33x_3 - 696.71 \leq 16000.00 \\ g_5(\mathbf{x}) &= \frac{2.138}{x_1 x_2} + 7883.39x_3 - 705.04 \leq 10000.00 \\ g_6(\mathbf{x}) &= \frac{0.417}{x_1 x_2} + 1721.26x_3 - 136.54 \leq 2000.00 \\ g_7(\mathbf{x}) &= \frac{0.164}{x_1 x_2} + 631.13x_3 - 54.48 \leq 550.00 \\ \mathbf{x}^{L} &\leq \mathbf{x} \leq \mathbf{x}^{U}, \end{align} where the lower and upper bounds on the variables are \[ \mathbf{x}^{L} = (0.01,\,0.01,\,0.01), \qquad \mathbf{x}^{U} = (0.45,\,0.10,\,0.10). \] Arguments: six_obj (bool): If False, use the original 5 objectives. If true, use the sum of contraint violations as the 6th objective. Default is False. References: Ray, T., Tai, K., & Seow, K. C. (2001). Multiobjective design optimization by an evolutionary algorithm. Engineering Optimization, 33(4), 399-424. (Section 4.4.) Returns: Problem: an instance of the water management problem. """ x_1 = Variable( name="x_1", symbol="x_1", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.45, initial_value=0.2, ) x_2 = Variable( name="x_2", symbol="x_2", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.10, initial_value=0.05, ) x_3 = Variable( name="x_3", symbol="x_3", variable_type=VariableTypeEnum.real, lowerbound=0.01, upperbound=0.10, initial_value=0.05, ) # Constraints g_1 = Constraint( name="g_1", symbol="g_1", cons_type=ConstraintTypeEnum.LTE, func="0.00139 / (x_1 * x_2) + 4.94 * x_3 - 0.08 - 1.00", is_linear=False, ) g_2 = Constraint( name="g_2", symbol="g_2", cons_type=ConstraintTypeEnum.LTE, func="0.000306 / (x_1 * x_2) + 1.082 * x_3 - 0.0986 - 1.00", is_linear=False, ) g_3 = Constraint( name="g_3", symbol="g_3", cons_type=ConstraintTypeEnum.LTE, func="12.307 / (x_1 * x_2) + 49408.24 * x_3 + 4051.02 - 50000.00", is_linear=False, ) g_4 = Constraint( name="g_4", symbol="g_4", cons_type=ConstraintTypeEnum.LTE, func="2.098 / (x_1 * x_2) + 8046.33 * x_3 - 696.71 - 16000.00", is_linear=False, ) g_5 = Constraint( name="g_5", symbol="g_5", cons_type=ConstraintTypeEnum.LTE, func="2.138 / (x_1 * x_2) + 7883.39 * x_3 - 705.04 - 10000.00", is_linear=False, ) g_6 = Constraint( name="g_6", symbol="g_6", cons_type=ConstraintTypeEnum.LTE, func="0.417 / (x_1 * x_2) + 1721.26 * x_3 - 136.54 - 2000.00", is_linear=False, ) g_7 = Constraint( name="g_7", symbol="g_7", cons_type=ConstraintTypeEnum.LTE, func="0.164 / (x_1 * x_2) + 631.13 * x_3 - 54.48 - 550.00", is_linear=False, ) # Objectives f_1 = Objective( name="f_1", symbol="f_1", func="106780.37 * (x_2 + x_3) + 61704.67", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=True, is_twice_differentiable=True, ) f_2 = Objective( name="f_2", symbol="f_2", func="3000 * x_1", objective_type=ObjectiveTypeEnum.analytical, is_linear=True, is_convex=True, is_twice_differentiable=True, ) f_3 = Objective( name="f_3", symbol="f_3", func="(305700 * 2289.0 * x_2)/((0.06*2289)**0.65)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=True, is_twice_differentiable=True, ) f_4 = Objective( name="f_4", symbol="f_4", func="250 * 2289 * Exp(-39.75 * x_2 + 9.9 * x_3 + 2.74)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=True, is_twice_differentiable=True, ) f_5 = Objective( name="f_5", symbol="f_5", func="25 * ((1.39 / (x_1 * x_2)) + 4940 * x_3 - 80)", objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=True, is_twice_differentiable=True, ) objectives = [f_1, f_2, f_3, f_4, f_5] if six_obj: big_func = ( "Max(0.00139 / (x_1 * x_2) + 4.94 * x_3 - 0.08 - 1.00, 0)" " + Max(0.000306 / (x_1 * x_2) + 1.082 * x_3 - 0.0986 - 1.00, 0)" " + Max(12.307 / (x_1 * x_2) + 49408.24 * x_3 + 4051.02 - 50000.00, 0)" " + Max(2.098 / (x_1 * x_2) + 8046.33 * x_3 - 696.71 - 16000.00, 0)" " + Max(2.138 / (x_1 * x_2) + 7883.39 * x_3 - 705.04 - 10000.00, 0)" " + Max(0.417 / (x_1 * x_2) + 1721.26 * x_3 - 136.54 - 2000.00, 0)" " + Max(0.164 / (x_1 * x_2) + 631.13 * x_3 - 54.48 - 550.00, 0)" ) f_6 = Objective( name="f_6", symbol="f_6", func=big_func, objective_type=ObjectiveTypeEnum.analytical, is_linear=False, is_convex=True, is_twice_differentiable=False, ) objectives.append(f_6) return Problem( name="water_management_problem", description="Water resource planning problem", variables=[x_1, x_2, x_3], objectives=objectives, constraints=[ g_1, g_2, g_3, g_4, g_5, g_6, g_7, ], ) ``` ### zdt1 ``` zdt1(number_of_variables: int) -> Problem ``` Defines the ZDT1 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: [\\begin{align\*} \\min\\quad f_1(\\textbf{x}) &= x_1 \\ \\min\\quad f_2(\\textbf{x}) &= g(\\textbf{x}) \\cdot h(f_1(\\textbf{x}), g(\\textbf{x}))\\ g(\\textbf{x}) &= 1 + \\frac{9}{n-1} \\sum\_{i=2}^{n} x_i \\ h(f_1, g) &= 1 - \\sqrt{\\frac{f_1}{g}}, \\ \\end{align\*}] where (f_1) and (f_2) are objective functions, (x_1,\\dots,x_n) are decision variable, (n) is the number of decision variables, and (g) and (h) are auxiliary functions. Source code in `desdeo/problem/testproblems/zdt_problem.py` ``` def zdt1(number_of_variables: int) -> Problem: r"""Defines the ZDT1 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: \begin{align*} \min\quad f_1(\textbf{x}) &= x_1 \\ \min\quad f_2(\textbf{x}) &= g(\textbf{x}) \cdot h(f_1(\textbf{x}), g(\textbf{x}))\\ g(\textbf{x}) &= 1 + \frac{9}{n-1} \sum_{i=2}^{n} x_i \\ h(f_1, g) &= 1 - \sqrt{\frac{f_1}{g}}, \\ \end{align*} where $f_1$ and $f_2$ are objective functions, $x_1,\dots,x_n$ are decision variable, $n$ is the number of decision variables, and $g$ and $h$ are auxiliary functions. """ n = number_of_variables # function f_1 f1_symbol = "f_1" f1_expr = "x_1" # function g g_symbol = "g" g_expr_1 = f"1 + (9 / ({n} - 1))" g_expr_2 = "(" + " + ".join([f"x_{i}" for i in range(2, n + 1)]) + ")" g_expr = g_expr_1 + " * " + g_expr_2 # function h(f, g) h_symbol = "h" h_expr = f"1 - Sqrt(({f1_expr}) / ({g_expr}))" # function f_2 f2_symbol = "f_2" f2_expr = f"{g_symbol} * {h_symbol}" variables = [ Variable(name=f"x_{i}", symbol=f"x_{i}", variable_type="real", lowerbound=0, upperbound=1, initial_value=0.5) for i in range(1, n + 1) ] objectives = [ Objective( name="f_1", symbol=f1_symbol, func=f1_expr, maximize=False, ideal=0, nadir=1, is_convex=True, is_linear=True, is_twice_differentiable=True, ), Objective( name="f_2", symbol=f2_symbol, func=f2_expr, maximize=False, ideal=0, nadir=1, is_convex=True, is_linear=False, is_twice_differentiable=True, ), ] extras = [ ExtraFunction( name="g", symbol=g_symbol, func=g_expr, is_convex=True, is_linear=True, is_twice_differentiable=True ), ExtraFunction( name="h", symbol=h_symbol, func=h_expr, is_convex=True, is_linear=False, is_twice_differentiable=True ), ] return Problem( name="zdt1", description="The ZDT1 test problem.", variables=variables, objectives=objectives, extra_funcs=extras, is_convex=True, is_linear=False, is_twice_differentiable=True, ) ``` ### zdt2 ``` zdt2(n_variables: int) -> Problem ``` Defines the ZDT2 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: [\\begin{align\*} \\min\\quad f_1(\\textbf{x}) &= x_1 \\ \\min\\quad f_2(\\textbf{x}) &= g(\\textbf{x}) \\cdot h(f_1(\\textbf{x}), g(\\textbf{x}))\\ g(\\textbf{x}) &= 1 + \\frac{9}{n-1} \\sum\_{i=2}^{n} x_i \\ h(f_1, g) &= 1 - \\left({\\frac{f_1}{g}}\\right)^2, \\ \\end{align\*}] where (f_1) and (f_2) are objective functions, (x_1,\\dots,x_n) are decision variable, (n) is the number of decision variables, and (g) and (h) are auxiliary functions. Source code in `desdeo/problem/testproblems/zdt_problem.py` ``` def zdt2(n_variables: int) -> Problem: r"""Defines the ZDT2 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: \begin{align*} \min\quad f_1(\textbf{x}) &= x_1 \\ \min\quad f_2(\textbf{x}) &= g(\textbf{x}) \cdot h(f_1(\textbf{x}), g(\textbf{x}))\\ g(\textbf{x}) &= 1 + \frac{9}{n-1} \sum_{i=2}^{n} x_i \\ h(f_1, g) &= 1 - \left({\frac{f_1}{g}}\right)^2, \\ \end{align*} where $f_1$ and $f_2$ are objective functions, $x_1,\dots,x_n$ are decision variable, $n$ is the number of decision variables, and $g$ and $h$ are auxiliary functions. """ n = n_variables # function f_1 f1_symbol = "f_1" f1_expr = "x_1" # function g g_symbol = "g" g_expr_1 = f"1 + (9 / ({n} - 1))" g_expr_2 = "(" + " + ".join([f"x_{i}" for i in range(2, n + 1)]) + ")" g_expr = g_expr_1 + " * " + g_expr_2 # function h(f, g) h_symbol = "h" h_expr = f"1 - (({f1_expr}) / ({g_expr})) ** 2" # function f_2 f2_symbol = "f_2" f2_expr = f"{g_symbol} * {h_symbol}" variables = [ Variable(name=f"x_{i}", symbol=f"x_{i}", variable_type="real", lowerbound=0, upperbound=1, initial_value=0.5) for i in range(1, n + 1) ] objectives = [ Objective( name="f_1", symbol=f1_symbol, func=f1_expr, maximize=False, ideal=0, nadir=1, is_convex=True, is_linear=True, is_twice_differentiable=True, ), Objective( name="f_2", symbol=f2_symbol, func=f2_expr, maximize=False, ideal=0, nadir=1, is_convex=False, is_linear=False, is_twice_differentiable=True, ), ] extras = [ ExtraFunction( name="g", symbol=g_symbol, func=g_expr, is_convex=True, is_linear=True, is_twice_differentiable=True ), ExtraFunction( name="h", symbol=h_symbol, func=h_expr, is_convex=False, is_linear=False, is_twice_differentiable=True ), ] return Problem( name="zdt2", description="The ZDT2 test problem.", variables=variables, objectives=objectives, extra_funcs=extras, is_convex=False, is_linear=False, is_twice_differentiable=True, ) ``` ### zdt3 ``` zdt3(n_variables: int) -> Problem ``` Defines the ZDT3 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: [\\begin{align\*} \\min\\quad f_1(x) &= x_1 \\ \\min\\quad f_2(x) &= g(\\textbf{x}) \\cdot h(f_1(\\textbf{x}), g(\\textbf{x}))\\ g(\\textbf{x}) &= 1 + \\frac{9}{n-1} \\sum\_{i=2}^{n} x_i \\ h(f_1, g) &= 1 - \\sqrt{\\frac{f_1}{g}} - \\frac{f_1}{g} \\sin(10\\pi f_1)), \\ \\end{align\*}] where (f_1) and (f_2) are objective functions, (x_1,\\dots,x_n) are decision variables, (n) is the number of decision variables, and (g) and (h) are auxiliary functions. Source code in `desdeo/problem/testproblems/zdt_problem.py` ``` def zdt3( n_variables: int, ) -> Problem: r"""Defines the ZDT3 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: \begin{align*} \min\quad f_1(x) &= x_1 \\ \min\quad f_2(x) &= g(\textbf{x}) \cdot h(f_1(\textbf{x}), g(\textbf{x}))\\ g(\textbf{x}) &= 1 + \frac{9}{n-1} \sum_{i=2}^{n} x_i \\ h(f_1, g) &= 1 - \sqrt{\frac{f_1}{g}} - \frac{f_1}{g} \sin(10\pi f_1)), \\ \end{align*} where $f_1$ and $f_2$ are objective functions, $x_1,\dots,x_n$ are decision variables, $n$ is the number of decision variables, and $g$ and $h$ are auxiliary functions. """ n = n_variables # function f_1 f1_symbol = "f_1" f1_expr = "x_1" # function g g_symbol = "g" g_expr_1 = f"1 + (9 / ({n} - 1))" g_expr_2 = "(" + " + ".join([f"x_{i}" for i in range(2, n + 1)]) + ")" g_expr = g_expr_1 + " * " + g_expr_2 # function h(f, g) h_symbol = "h" h_expr = f"1 - Sqrt(({f1_expr}) / ({g_expr})) - (({f1_expr}) / ({g_expr})) * Sin (10 * {pi} * {f1_expr}) " # function f_2 f2_symbol = "f_2" f2_expr = f"{g_symbol} * {h_symbol}" variables = [ Variable(name=f"x_{i}", symbol=f"x_{i}", variable_type="real", lowerbound=0, upperbound=1, initial_value=0.5) for i in range(1, n + 1) ] objectives = [ Objective( name="f_1", symbol=f1_symbol, func=f1_expr, maximize=False, ideal=0, nadir=1, is_convex=True, is_linear=True, is_twice_differentiable=True, ), Objective( name="f_2", symbol=f2_symbol, func=f2_expr, maximize=False, ideal=-1, nadir=1, is_convex=False, is_linear=False, is_twice_differentiable=True, ), ] extras = [ ExtraFunction( name="g", symbol=g_symbol, func=g_expr, is_convex=True, is_linear=True, is_twice_differentiable=True ), ExtraFunction( name="h", symbol=h_symbol, func=h_expr, is_convex=False, is_linear=False, is_twice_differentiable=True ), ] return Problem( name="zdt3", description="The ZDT3 test problem.", variables=variables, objectives=objectives, extra_funcs=extras, is_convex=False, is_linear=False, is_twice_differentiable=True, ) ``` ### zdt4 ``` zdt4(number_of_variables: int) -> Problem ``` Defines the ZDT4 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: \[\\begin{align\*} \\min\\quad f_1(\\textbf{x}) &= x_1 \\ \\min\\quad f_2(\\text{x}) &=g(\\text{x})\\cdot\\left(h\\right) \\ g(\\text{x}) &=1+10\\left(n-1\\right)+\\sum\_{i=2}^n\\left[x_i^2-10\\cos\\left(4\\pi\\cdot x_i\\right)\\right]\\ h(f_1{,}g) &=1-\\sqrt{\\frac{f_1}{g}}, \\ \\end{align\*}\] where (f_1) and (f_2) are objective functions, (x_1,\\dots,x_n) are decision variables, (n) is the number of decision variables, and (g) and (h) are auxiliary functions. Source code in `desdeo/problem/testproblems/zdt_problem.py` ``` def zdt4(number_of_variables: int) -> Problem: r"""Defines the ZDT4 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: \begin{align*} \min\quad f_1(\textbf{x}) &= x_1 \\ \min\quad f_2(\text{x}) &=g(\text{x})\cdot\left(h\right) \\ g(\text{x}) &=1+10\left(n-1\right)+\sum_{i=2}^n\left[x_i^2-10\cos\left(4\pi\cdot x_i\right)\right]\\ h(f_1{,}g) &=1-\sqrt{\frac{f_1}{g}}, \\ \end{align*} where $f_1$ and $f_2$ are objective functions, $x_1,\dots,x_n$ are decision variables, $n$ is the number of decision variables, and $g$ and $h$ are auxiliary functions. """ n = number_of_variables # function f_1 f1_symbol = "f_1" f1_expr = "x_1" # function g g_symbol = "g" g_expr_1 = f"1 + 10 * ({n} - 1)" g_expr_2 = "(" + " + ".join([f"x_{i}**2 - 10 * Cos(4 * {pi} * x_{i})" for i in range(2, n + 1)]) + ")" g_expr = g_expr_1 + " + " + g_expr_2 # function h(f, g) h_symbol = "h" h_expr = f"1 - Sqrt(({f1_expr}) / ({g_expr}))" # function f_2 f2_symbol = "f_2" f2_expr = f"{g_symbol} * {h_symbol}" variables = [ Variable(name=f"x_{1}", symbol=f"x_{1}", variable_type="real", lowerbound=0, upperbound=1, initial_value=0.5), ] + [ Variable(name=f"x_{i}", symbol=f"x_{i}", variable_type="real", lowerbound=-5, upperbound=5, initial_value=0) for i in range(2, n + 1) ] objectives = [ Objective( name="f_1", symbol=f1_symbol, func=f1_expr, maximize=False, ideal=0, nadir=1, is_convex=True, is_linear=True, is_twice_differentiable=True, ), Objective( name="f_2", symbol=f2_symbol, func=f2_expr, maximize=False, ideal=0, nadir=1, is_convex=True, is_linear=False, is_twice_differentiable=True, ), ] extras = [ ExtraFunction( name="g", symbol=g_symbol, func=g_expr, is_convex=True, is_linear=True, is_twice_differentiable=True ), ExtraFunction( name="h", symbol=h_symbol, func=h_expr, is_convex=True, is_linear=False, is_twice_differentiable=True ), ] return Problem( name="zdt4", description="The ZDT4 test problem.", variables=variables, objectives=objectives, extra_funcs=extras, is_convex=True, is_linear=False, is_twice_differentiable=True, ) ``` ### zdt6 ``` zdt6(number_of_variables: int) -> Problem ``` Defines the ZDT6 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: \[\\begin{align\*} \\min\\quad f_1(\\textbf{x}) &= 1 -\\exp(-4x_1)\\sin^{6}(6\\pi x_1) \\ \\min\\quad f_2(\\textbf{x}) &= g(\\textbf{x})\\left[1-\\left(\\frac{f_1(\\textbf{x})} {g(\\textbf{x})}\\right)^{2}\\right] \\ g(\\textbf{x}) &= 1 + 9\\left(\\frac{\\sum\_{i=2}^{n} x_i}{n-1}\\right)^{0.25} \\end{align\*}\] where (f_1) and (f_2) are objective functions, (x_1,\\dots,x_n) are decision variables, (n) is the number of decision variables, and (g) is the auxillary function. Source code in `desdeo/problem/testproblems/zdt_problem.py` ``` def zdt6(number_of_variables: int) -> Problem: r"""Defines the ZDT6 test problem. The problem has a variable number of decision variables and two objective functions to be minimized as follows: \begin{align*} \min\quad f_1(\textbf{x}) &= 1 -\exp(-4x_1)\sin^{6}(6\pi x_1) \\ \min\quad f_2(\textbf{x}) &= g(\textbf{x})\left[1-\left(\frac{f_1(\textbf{x})} {g(\textbf{x})}\right)^{2}\right] \\ g(\textbf{x}) &= 1 + 9\left(\frac{\sum_{i=2}^{n} x_i}{n-1}\right)^{0.25} \end{align*} where $f_1$ and $f_2$ are objective functions, $x_1,\dots,x_n$ are decision variables, $n$ is the number of decision variables, and $g$ is the auxillary function. """ n = number_of_variables f1_symbol = "f_1" f1_expr = f"1 - Exp(-4*x_1)*(Sin(6*{pi}*x_1))**6" g_symbol = "g" g_expr_1 = " + ".join([f"x_{i}" for i in range(2, n + 1)]) g_expr = f"1 + 9 * ((({g_expr_1}) / ({n} - 1)) ** 0.25)" f2_symbol = "f_2" f2_expr = f"{g_symbol} * (1 - ({f1_symbol} / {g_symbol})**2)" variables = [ Variable(name=f"x_{i}", symbol=f"x_{i}", variable_type="real", lowerbound=0, upperbound=1, initial_value=0.5) for i in range(1, n + 1) ] objectives = [ Objective( name="f_1", symbol=f1_symbol, func=f1_expr, maximize=False, ideal=0, nadir=1, is_convex=False, is_linear=False, is_twice_differentiable=True, ), Objective( name="f_2", symbol=f2_symbol, func=f2_expr, maximize=False, ideal=0, nadir=1, is_convex=False, is_linear=False, is_twice_differentiable=True, ), ] extras = [ ExtraFunction( name="g", symbol=g_symbol, func=g_expr, is_convex=False, is_linear=False, is_twice_differentiable=True ), ] return Problem( name="zdt6", description="The ZDT6 test problem.", variables=variables, objectives=objectives, extra_funcs=extras, ) ``` ## Problem schema ### desdeo.problem.schema Schema for the problem definition. The problem definition is a JSON file that contains the following information: - Constants - Variables - Objectives - Extra functions - Scalarization functions - Evaluated solutions and their info #### Constant Bases: `BaseModel` Model for a constant. Source code in `desdeo/problem/schema.py` ``` class Constant(BaseModel): """Model for a constant.""" model_config = ConfigDict(frozen=True, from_attributes=True, extra="forbid") name: str = Field( description=( "Descriptive name of the constant. This can be used in UI and visualizations. Example: 'maximum cost'." ), ) """Descriptive name of the constant. This can be used in UI and visualizations." " Example: 'maximum cost'.""" symbol: str = Field( description=( "Symbol to represent the constant. This will be used in the rest of the problem definition." " It may also be used in UIs and visualizations. Example: 'c_1'." ), ) """ Symbol to represent the constant. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'c_1'.""" value: VariableType = Field(description="The value of the constant.") """The value of the constant.""" ``` ##### name ``` name: str = Field( description="Descriptive name of the constant. This can be used in UI and visualizations. Example: 'maximum cost'." ) ``` Descriptive name of the constant. This can be used in UI and visualizations." " Example: 'maximum cost'. ##### symbol ``` symbol: str = Field( description="Symbol to represent the constant. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'c_1'." ) ``` Symbol to represent the constant. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'c_1'. ##### value ``` value: VariableType = Field( description="The value of the constant." ) ``` The value of the constant. #### Constraint Bases: `BaseModel` Model for a constraint function. Source code in `desdeo/problem/schema.py` ``` class Constraint(BaseModel): """Model for a constraint function.""" model_config = ConfigDict(frozen=True, from_attributes=True, extra="forbid") name: str = Field( description=( "Descriptive name of the constraint. This can be used in UI and visualizations. Example: 'maximum length'." ), ) """ Descriptive name of the constraint. This can be used in UI and visualizations. Example: 'maximum length'""" symbol: str = Field( description=( "Symbol to represent the constraint. This will be used in the rest of the problem definition." " It may also be used in UIs and visualizations. Example: 'g_1'." ), ) """ Symbol to represent the constraint. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'g_1'. """ cons_type: ConstraintTypeEnum = Field( description=( "The type of the constraint. Constraints are assumed to be in a standard form where the supplied 'func'" " expression is on the left hand side of the constraint's expression, and on the right hand side a zero" " value is assume. The comparison between the left hand side and right hand side is either and quality" " comparison ('=') or lesser than equal comparison ('<=')." ) ) """ The type of the constraint. Constraints are assumed to be in a standard form where the supplied 'func' expression is on the left hand side of the constraint's expression, and on the right hand side a zero value is assume. The comparison between the left hand side and right hand side is either and quality comparison ('=') or lesser than equal comparison ('<=').""" func: list | None = Field( description=( "Function of the constraint. This is a JSON object that can be parsed into a function." "Must be a valid MathJSON object." " The symbols in the function must match objective/variable/constant symbols." "Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. " "If 'None', either 'simulator_path' or 'surrogates' must not be 'None'." ), default=None, ) """ Function of the constraint. This is a JSON object that can be parsed into a function. Must be a valid MathJSON object. The symbols in the function must match objective/variable/constant symbols. Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'.""" simulator_path: Path | Url | None = Field( description=( "Path to a python file with the connection to simulators. Must be a valid Path." "Can be 'None' for if either 'func' or 'surrogates' is not 'None'." "If 'None', either 'func' or 'surrogates' must not be 'None'." ), default=None, ) """Path to a python file with the connection to simulators. Must be a valid Path. Can be 'None' for if either 'func' or 'surrogates' is not 'None'. If 'None', either 'func' or 'surrogates' must not be 'None'.""" surrogates: list[Path] | None = Field( description=( "A list of paths to models saved on disk. Can be 'None' for if either 'func' or 'simulator_path' " "is not 'None'. If 'None', either 'func' or 'simulator_path' must not be 'None'." ), default=None, ) """A list of paths to models saved on disk. Can be 'None' for if either 'func' or 'simulator_path' is not 'None'. If 'None', either 'func' or 'simulator_path' must not be 'None'.""" is_linear: bool = Field( description="Whether the constraint is linear or not. Defaults to True, e.g., a linear constraint is assumed.", default=True, ) """Whether the constraint is linear or not. Defaults to True, e.g., a linear constraint is assumed. Defaults to `True`.""" is_convex: bool = Field( description="Whether the function expression is convex or not (non-convex). Defaults to `False`.", default=False ) """Whether the function expression is convex or not (non-convex). Defaults to `False`.""" is_twice_differentiable: bool = Field( description="Whether the function expression is twice differentiable or not. Defaults to `False`", default=False ) """Whether the function expression is twice differentiable or not. Defaults to `False`""" _parse_infix_to_func = field_validator("func", mode="before")(parse_infix_to_func) ``` ##### cons_type ``` cons_type: ConstraintTypeEnum = Field( description="The type of the constraint. Constraints are assumed to be in a standard form where the supplied 'func' expression is on the left hand side of the constraint's expression, and on the right hand side a zero value is assume. The comparison between the left hand side and right hand side is either and quality comparison ('=') or lesser than equal comparison ('<=')." ) ``` The type of the constraint. Constraints are assumed to be in a standard form where the supplied 'func' expression is on the left hand side of the constraint's expression, and on the right hand side a zero value is assume. The comparison between the left hand side and right hand side is either and quality comparison ('=') or lesser than equal comparison ('\<='). ##### func ``` func: list | None = Field( description="Function of the constraint. This is a JSON object that can be parsed into a function.Must be a valid MathJSON object. The symbols in the function must match objective/variable/constant symbols.Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'.", default=None, ) ``` Function of the constraint. This is a JSON object that can be parsed into a function. Must be a valid MathJSON object. The symbols in the function must match objective/variable/constant symbols. Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'. ##### is_convex ``` is_convex: bool = Field( description="Whether the function expression is convex or not (non-convex). Defaults to `False`.", default=False, ) ``` Whether the function expression is convex or not (non-convex). Defaults to `False`. ##### is_linear ``` is_linear: bool = Field( description="Whether the constraint is linear or not. Defaults to True, e.g., a linear constraint is assumed.", default=True, ) ``` Whether the constraint is linear or not. Defaults to True, e.g., a linear constraint is assumed. Defaults to `True`. ##### is_twice_differentiable ``` is_twice_differentiable: bool = Field( description="Whether the function expression is twice differentiable or not. Defaults to `False`", default=False, ) ``` Whether the function expression is twice differentiable or not. Defaults to `False` ##### name ``` name: str = Field( description="Descriptive name of the constraint. This can be used in UI and visualizations. Example: 'maximum length'." ) ``` Descriptive name of the constraint. This can be used in UI and visualizations. Example: 'maximum length' ##### simulator_path ``` simulator_path: Path | Url | None = Field( description="Path to a python file with the connection to simulators. Must be a valid Path.Can be 'None' for if either 'func' or 'surrogates' is not 'None'.If 'None', either 'func' or 'surrogates' must not be 'None'.", default=None, ) ``` Path to a python file with the connection to simulators. Must be a valid Path. Can be 'None' for if either 'func' or 'surrogates' is not 'None'. If 'None', either 'func' or 'surrogates' must not be 'None'. ##### surrogates ``` surrogates: list[Path] | None = Field( description="A list of paths to models saved on disk. Can be 'None' for if either 'func' or 'simulator_path' is not 'None'. If 'None', either 'func' or 'simulator_path' must not be 'None'.", default=None, ) ``` A list of paths to models saved on disk. Can be 'None' for if either 'func' or 'simulator_path' is not 'None'. If 'None', either 'func' or 'simulator_path' must not be 'None'. ##### symbol ``` symbol: str = Field( description="Symbol to represent the constraint. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'g_1'." ) ``` Symbol to represent the constraint. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'g_1'. #### ConstraintTypeEnum Bases: `StrEnum` An enumerator for supported constraint expression types. Source code in `desdeo/problem/schema.py` ``` class ConstraintTypeEnum(StrEnum): """An enumerator for supported constraint expression types.""" EQ = "=" """An equality constraint.""" LTE = "<=" # less than or equal """An inequality constraint of type 'less than or equal'.""" ``` ##### EQ ``` EQ = '=' ``` An equality constraint. ##### LTE ``` LTE = '<=' ``` An inequality constraint of type 'less than or equal'. #### DiscreteRepresentation Bases: `BaseModel` Model to represent discrete objective function and decision variable pairs. Can be used alongside an analytical representation as well. Used with Objectives of type 'data_based' by default. Each of the decision variable values and objective functions values are ordered in their respective dict entries. This means that the decision variable values found at `variable_values['x_i'][j]` correspond to the objective function values found at `objective_values['f_i'][j]` for all `i` and some `j`. Source code in `desdeo/problem/schema.py` ``` class DiscreteRepresentation(BaseModel): """Model to represent discrete objective function and decision variable pairs. Can be used alongside an analytical representation as well. Used with Objectives of type 'data_based' by default. Each of the decision variable values and objective functions values are ordered in their respective dict entries. This means that the decision variable values found at `variable_values['x_i'][j]` correspond to the objective function values found at `objective_values['f_i'][j]` for all `i` and some `j`. """ model_config = ConfigDict(frozen=True, from_attributes=True, extra="forbid") variable_values: dict[str, list[VariableType]] = Field( description=( "A dictionary with decision variable values. Each dict key points to a list of all the decision " "variable values available for the decision variable given in the key. " "The keys must match the 'symbols' defined for the decision variables." ) ) """ A dictionary with decision variable values. Each dict key points to a list of all the decision variable values available for the decision variable given in the key. The keys must match the 'symbols' defined for the decision variables.""" objective_values: dict[str, list[float]] = Field( description=( "A dictionary with objective function values. Each dict key points to a list of all the objective " "function values available for the objective function given in the key. The keys must match the 'symbols' " "defined for the objective functions." ) ) """ A dictionary with objective function values. Each dict key points to a list of all the objective function values available for the objective function given in the key. The keys must match the 'symbols' defined for the objective functions.""" non_dominated: bool = Field( description=( "Indicates whether the representation consists of non-dominated points or not." "If False, some method can employ non-dominated sorting, which might slow an interactive method down." ), default=False, ) """ Indicates whether the representation consists of non-dominated points or not. If False, some method can employ non-dominated sorting, which might slow an interactive method down. Defaults to `False`.""" ``` ##### non_dominated ``` non_dominated: bool = Field( description="Indicates whether the representation consists of non-dominated points or not.If False, some method can employ non-dominated sorting, which might slow an interactive method down.", default=False, ) ``` Indicates whether the representation consists of non-dominated points or not. If False, some method can employ non-dominated sorting, which might slow an interactive method down. Defaults to `False`. ##### objective_values ``` objective_values: dict[str, list[float]] = Field( description="A dictionary with objective function values. Each dict key points to a list of all the objective function values available for the objective function given in the key. The keys must match the 'symbols' defined for the objective functions." ) ``` A dictionary with objective function values. Each dict key points to a list of all the objective function values available for the objective function given in the key. The keys must match the 'symbols' defined for the objective functions. ##### variable_values ``` variable_values: dict[str, list[VariableType]] = Field( description="A dictionary with decision variable values. Each dict key points to a list of all the decision variable values available for the decision variable given in the key. The keys must match the 'symbols' defined for the decision variables." ) ``` A dictionary with decision variable values. Each dict key points to a list of all the decision variable values available for the decision variable given in the key. The keys must match the 'symbols' defined for the decision variables. #### ExtraFunction Bases: `BaseModel` Model for extra functions. These functions can, e.g., be functions that are re-used in the problem formulation, or they are needed for other computations related to the problem. Source code in `desdeo/problem/schema.py` ``` class ExtraFunction(BaseModel): """Model for extra functions. These functions can, e.g., be functions that are re-used in the problem formulation, or they are needed for other computations related to the problem. """ model_config = ConfigDict(frozen=True, from_attributes=True, extra="forbid") name: str = Field( description=("Descriptive name of the function. Example: 'normalization'."), ) """Descriptive name of the function. Example: 'normalization'.""" symbol: str = Field( description=( "Symbol to represent the function. This will be used in the rest of the problem definition." " It may also be used in UIs and visualizations. Example: 'avg'." ), ) """ Symbol to represent the function. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'avg'.""" func: list | None = Field( description=( "The string representing the function. This is a JSON object that can be parsed into a function." "Must be a valid MathJSON object." " The symbols in the function must match symbols defined for objective/variable/constant." "Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. " "If 'None', either 'simulator_path' or 'surrogates' must not be 'None'." ), default=None, ) """ The string representing the function. This is a JSON object that can be parsed into a function. Must be a valid MathJSON object. The symbols in the function must match symbols defined for objective/variable/constant. Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'.""" simulator_path: Path | None = Field( description=( "Path to a python file with the connection to simulators. Must be a valid Path." "Can be 'None' for 'analytical', 'data_based' or 'surrogate' functions." "If 'None', either 'func' or 'surrogates' must not be 'None'." ), default=None, ) """Path to a python file with the connection to simulators. Must be a valid Path. Can be 'None' for 'analytical', 'data_based' or 'surrogate' functions. If 'None', either 'func' or 'surrogates' must not be 'None'.""" surrogates: list[Path] | None = Field( description=( "A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based " "or 'simulator' functions. If 'None', either 'func' or 'simulator_path' must " "not be 'None'." ), default=None, ) """A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based or 'simulator' functions. If 'None', either 'func' or 'simulator_path' must not be 'None'.""" is_linear: bool = Field( description="Whether the function expression is linear or not. Defaults to `False`.", default=False ) """Whether the function expression is linear or not. Defaults to `False`.""" is_convex: bool = Field( description="Whether the function expression is convex or not (non-convex). Defaults to `False`.", default=False ) """Whether the function expression is convex or not (non-convex). Defaults to `False`.""" is_twice_differentiable: bool = Field( description="Whether the function expression is twice differentiable or not. Defaults to `False`", default=False ) """Whether the function expression is twice differentiable or not. Defaults to `False`""" _parse_infix_to_func = field_validator("func", mode="before")(parse_infix_to_func) ``` ##### func ``` func: list | None = Field( description="The string representing the function. This is a JSON object that can be parsed into a function.Must be a valid MathJSON object. The symbols in the function must match symbols defined for objective/variable/constant.Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'.", default=None, ) ``` The string representing the function. This is a JSON object that can be parsed into a function. Must be a valid MathJSON object. The symbols in the function must match symbols defined for objective/variable/constant. Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'. ##### is_convex ``` is_convex: bool = Field( description="Whether the function expression is convex or not (non-convex). Defaults to `False`.", default=False, ) ``` Whether the function expression is convex or not (non-convex). Defaults to `False`. ##### is_linear ``` is_linear: bool = Field( description="Whether the function expression is linear or not. Defaults to `False`.", default=False, ) ``` Whether the function expression is linear or not. Defaults to `False`. ##### is_twice_differentiable ``` is_twice_differentiable: bool = Field( description="Whether the function expression is twice differentiable or not. Defaults to `False`", default=False, ) ``` Whether the function expression is twice differentiable or not. Defaults to `False` ##### name ``` name: str = Field( description="Descriptive name of the function. Example: 'normalization'." ) ``` Descriptive name of the function. Example: 'normalization'. ##### simulator_path ``` simulator_path: Path | None = Field( description="Path to a python file with the connection to simulators. Must be a valid Path.Can be 'None' for 'analytical', 'data_based' or 'surrogate' functions.If 'None', either 'func' or 'surrogates' must not be 'None'.", default=None, ) ``` Path to a python file with the connection to simulators. Must be a valid Path. Can be 'None' for 'analytical', 'data_based' or 'surrogate' functions. If 'None', either 'func' or 'surrogates' must not be 'None'. ##### surrogates ``` surrogates: list[Path] | None = Field( description="A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based or 'simulator' functions. If 'None', either 'func' or 'simulator_path' must not be 'None'.", default=None, ) ``` A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based or 'simulator' functions. If 'None', either 'func' or 'simulator_path' must not be 'None'. ##### symbol ``` symbol: str = Field( description="Symbol to represent the function. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'avg'." ) ``` Symbol to represent the function. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'avg'. #### Objective Bases: `BaseModel` Model for an objective function. Source code in `desdeo/problem/schema.py` ``` class Objective(BaseModel): """Model for an objective function.""" model_config = ConfigDict(frozen=True, from_attributes=True, extra="forbid") """A longer description for the objective.""" description: str | None = Field( description=( "A longer description of the objective function. This can be used in UI and visualizations. \ Meant to have longer text than what name should have." ), default=None, ) name: str = Field( description=( "Descriptive name of the objective function. This can be used in UI and visualizations. Example: 'time'." ), ) """Descriptive name of the objective function. This can be used in UI and visualizations.""" symbol: str = Field( description=( "Symbol to represent the objective function. This will be used in the rest of the problem definition." " It may also be used in UIs and visualizations. Example: 'f_1'." ), ) """ Symbol to represent the objective function. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'f_1'.""" unit: str | None = Field( description=( "The unit of the objective function. This is optional. Used in UIs and visualizations. Example: 'seconds'" " or 'millions of hectares'." ), default=None, ) """The unit of the objective function. This is optional. Used in UIs and visualizations. Example: 'seconds' or 'millions of hectares'. Defaults to `None`.""" func: list | None = Field( description=( "The objective function. This is a JSON object that can be parsed into a function." "Must be a valid MathJSON object. The symbols in the function must match the symbols defined for " "variable/constant/extra function. Can be 'None' for 'data_based', 'simulator' or " "'surrogate' objective functions. If 'None', either 'simulator_path' or 'surrogates' must " "not be 'None'." ), default=None, ) """ The objective function. This is a JSON object that can be parsed into a function. Must be a valid MathJSON object. The symbols in the function must match the symbols defined for variable/constant/extra function. Can be 'None' for 'data_based', 'simulator' or 'surrogate' objective functions. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'.""" simulator_path: Path | Url | None = Field( description=( "Path to a python file or http server with the connection to simulators. Must be a valid Path or url." "Can be 'None' for 'analytical', 'data_based' or 'surrogate' objective functions." "If 'None', either 'func' or 'surrogates' must not be 'None'." ), default=None, ) """Path to a python file with the connection to simulators. Must be a valid Path. Can be 'None' for 'analytical', 'data_based' or 'surrogate' objective functions. If 'None', either 'func' or 'surrogates' must not be 'None'.""" surrogates: list[Path] | None = Field( description=( "A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based " "or 'simulator' objective functions. If 'None', either 'func' or 'simulator_path' must " "not be 'None'." ), default=None, ) """A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based or 'simulator' objective functions. If 'None', either 'func' or 'simulator_path' must not be 'None'.""" maximize: bool = Field( description="Whether the objective function is to be maximized or minimized.", default=False, ) """Whether the objective function is to be maximized or minimized. Defaults to `False`.""" ideal: float | None = Field(description="Ideal value of the objective. This is optional.", default=None) """Ideal value of the objective. This is optional. Defaults to `None`.""" nadir: float | None = Field(description="Nadir value of the objective. This is optional.", default=None) """Nadir value of the objective. This is optional. Defaults to `None`.""" objective_type: ObjectiveTypeEnum = Field( description=( "The type of objective function. 'analytical' means the objective function value is calculated " "based on 'func'. 'data_based' means the objective function value should be retrieved from a table. " "In case of 'data_based' objective function, the 'func' field is ignored. Defaults to 'analytical'." ), default=ObjectiveTypeEnum.analytical, ) """ The type of objective function. 'analytical' means the objective function value is calculated based on 'func'. 'data_based' means the objective function value should be retrieved from a table. In case of 'data_based' objective function, the 'func' field is ignored. Defaults to 'analytical'. Defaults to 'analytical'.""" is_linear: bool = Field( description="Whether the function expression is linear or not. Defaults to `False`.", default=False ) """Whether the function expression is linear or not. Defaults to `False`.""" is_convex: bool = Field( description="Whether the function expression is convex or not (non-convex). Defaults to `False`.", default=False ) """Whether the function expression is convex or not (non-convex). Defaults to `False`.""" is_twice_differentiable: bool = Field( description="Whether the function expression is twice differentiable or not. Defaults to `False`", default=False ) """Whether the function expression is twice differentiable or not. Defaults to `False`""" _parse_infix_to_func = field_validator("func", mode="before")(parse_infix_to_func) ``` ##### func ``` func: list | None = Field( description="The objective function. This is a JSON object that can be parsed into a function.Must be a valid MathJSON object. The symbols in the function must match the symbols defined for variable/constant/extra function. Can be 'None' for 'data_based', 'simulator' or 'surrogate' objective functions. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'.", default=None, ) ``` The objective function. This is a JSON object that can be parsed into a function. Must be a valid MathJSON object. The symbols in the function must match the symbols defined for variable/constant/extra function. Can be 'None' for 'data_based', 'simulator' or 'surrogate' objective functions. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'. ##### ideal ``` ideal: float | None = Field( description="Ideal value of the objective. This is optional.", default=None, ) ``` Ideal value of the objective. This is optional. Defaults to `None`. ##### is_convex ``` is_convex: bool = Field( description="Whether the function expression is convex or not (non-convex). Defaults to `False`.", default=False, ) ``` Whether the function expression is convex or not (non-convex). Defaults to `False`. ##### is_linear ``` is_linear: bool = Field( description="Whether the function expression is linear or not. Defaults to `False`.", default=False, ) ``` Whether the function expression is linear or not. Defaults to `False`. ##### is_twice_differentiable ``` is_twice_differentiable: bool = Field( description="Whether the function expression is twice differentiable or not. Defaults to `False`", default=False, ) ``` Whether the function expression is twice differentiable or not. Defaults to `False` ##### maximize ``` maximize: bool = Field( description="Whether the objective function is to be maximized or minimized.", default=False, ) ``` Whether the objective function is to be maximized or minimized. Defaults to `False`. ##### model_config ``` model_config = ConfigDict( frozen=True, from_attributes=True, extra="forbid" ) ``` A longer description for the objective. ##### nadir ``` nadir: float | None = Field( description="Nadir value of the objective. This is optional.", default=None, ) ``` Nadir value of the objective. This is optional. Defaults to `None`. ##### name ``` name: str = Field( description="Descriptive name of the objective function. This can be used in UI and visualizations. Example: 'time'." ) ``` Descriptive name of the objective function. This can be used in UI and visualizations. ##### objective_type ``` objective_type: ObjectiveTypeEnum = Field( description="The type of objective function. 'analytical' means the objective function value is calculated based on 'func'. 'data_based' means the objective function value should be retrieved from a table. In case of 'data_based' objective function, the 'func' field is ignored. Defaults to 'analytical'.", default=ObjectiveTypeEnum.analytical, ) ``` The type of objective function. 'analytical' means the objective function value is calculated based on 'func'. 'data_based' means the objective function value should be retrieved from a table. In case of 'data_based' objective function, the 'func' field is ignored. Defaults to 'analytical'. Defaults to 'analytical'. ##### simulator_path ``` simulator_path: Path | Url | None = Field( description="Path to a python file or http server with the connection to simulators. Must be a valid Path or url.Can be 'None' for 'analytical', 'data_based' or 'surrogate' objective functions.If 'None', either 'func' or 'surrogates' must not be 'None'.", default=None, ) ``` Path to a python file with the connection to simulators. Must be a valid Path. Can be 'None' for 'analytical', 'data_based' or 'surrogate' objective functions. If 'None', either 'func' or 'surrogates' must not be 'None'. ##### surrogates ``` surrogates: list[Path] | None = Field( description="A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based or 'simulator' objective functions. If 'None', either 'func' or 'simulator_path' must not be 'None'.", default=None, ) ``` A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based or 'simulator' objective functions. If 'None', either 'func' or 'simulator_path' must not be 'None'. ##### symbol ``` symbol: str = Field( description="Symbol to represent the objective function. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'f_1'." ) ``` Symbol to represent the objective function. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'f_1'. ##### unit ``` unit: str | None = Field( description="The unit of the objective function. This is optional. Used in UIs and visualizations. Example: 'seconds' or 'millions of hectares'.", default=None, ) ``` The unit of the objective function. This is optional. Used in UIs and visualizations. Example: 'seconds' or 'millions of hectares'. Defaults to `None`. #### ObjectiveTypeEnum Bases: `StrEnum` An enumerator for supported objective function types. Source code in `desdeo/problem/schema.py` ``` class ObjectiveTypeEnum(StrEnum): """An enumerator for supported objective function types.""" analytical = "analytical" """An objective function with an analytical formulation. E.g., it can be expressed with mathematical expressions, such as x_1 + x_2.""" data_based = "data_based" """A data-based objective function. It is assumed that when such an objective is present in a `Problem`, then there is a `DiscreteRepresentation` available with values representing the objective function.""" simulator = "simulator" """A simulator based objective function. It is assumed that a Path (str) to a simulator file that connects a simulator to DESDEO is present in the `Objective` and also in the list of simulators in the `Problem`.""" surrogate = "surrogate" """A surrogate based objective function. It is assumed that a Path (str) to a surrogate saved on the disk is present in the `Objective` and also in the list of simulators in the `Problem`.""" ``` ##### analytical ``` analytical = 'analytical' ``` An objective function with an analytical formulation. E.g., it can be expressed with mathematical expressions, such as x_1 + x_2. ##### data_based ``` data_based = 'data_based' ``` A data-based objective function. It is assumed that when such an objective is present in a `Problem`, then there is a `DiscreteRepresentation` available with values representing the objective function. ##### simulator ``` simulator = 'simulator' ``` A simulator based objective function. It is assumed that a Path (str) to a simulator file that connects a simulator to DESDEO is present in the `Objective` and also in the list of simulators in the `Problem`. ##### surrogate ``` surrogate = 'surrogate' ``` A surrogate based objective function. It is assumed that a Path (str) to a surrogate saved on the disk is present in the `Objective` and also in the list of simulators in the `Problem`. #### Problem Bases: `BaseModel` Model for a problem definition. Source code in `desdeo/problem/schema.py` ``` class Problem(BaseModel): """Model for a problem definition.""" model_config = ConfigDict(frozen=True, extra="forbid") _scalarization_index: int = PrivateAttr(default=1) # TODO: make init to communicate the _scalarization_index to a new model @classmethod def from_problemdb(cls, db_instance: "ProblemDB") -> "Problem": """.""" constants = [Constant.model_validate(const) for const in db_instance.constants] + [ TensorConstant.model_validate(const) for const in db_instance.tensor_constants ] return cls( name=db_instance.name, description=db_instance.description, is_convex=db_instance.is_convex, is_linear=db_instance.is_linear, is_twice_differentiable=db_instance.is_twice_differentiable, constants=constants if constants != [] else None, variables=[Variable.model_validate(var) for var in db_instance.variables] + [TensorVariable.model_validate(var) for var in db_instance.tensor_variables], objectives=[Objective.model_validate(obj) for obj in db_instance.objectives], constraints=[Constraint.model_validate(const) for const in db_instance.constraints] if db_instance.constraints != [] else None, scalarization_funcs=[ScalarizationFunction.model_validate(scal) for scal in db_instance.scalarization_funcs] if db_instance.scalarization_funcs != [] else None, extra_funcs=[ExtraFunction.model_validate(extra) for extra in db_instance.extra_funcs] if db_instance.extra_funcs != [] else None, discrete_representation=DiscreteRepresentation.model_validate(db_instance.discrete_representation) if db_instance.discrete_representation is not None else None, simulators=[Simulator.model_validate(sim) for sim in db_instance.simulators] if db_instance.simulators != [] else None, ) @model_validator(mode="after") def set_default_scalarization_names(self) -> "Problem": """Check the scalarization functions for symbols with value 'None'. If found, names them systematically 'scal_i', where 'i' is a running index stored in an instance attribute. """ if self.scalarization_funcs is None: return self for func in self.scalarization_funcs: if func.symbol is None: func.symbol = f"scal_{self._scalarization_index}" self._scalarization_index += 1 return self @model_validator(mode="after") def check_for_non_unique_symbols(self) -> "Problem": """Check that all the symbols defined in the different fields are unique.""" symbols = self.get_all_symbols() # symbol is always populated symbol_counts = Counter(symbols) # collect duplicates, if they exist duplicates = {symbol: count for symbol, count in symbol_counts.items() if count > 1} if duplicates: # if any duplicates are found, raise a value error and report the duplicate symbols. msg = "Non-unique symbols found in the Problem model." for symbol, count in duplicates.items(): msg += f" Symbol '{symbol}' occurs {count} times." raise ValueError(msg) return self def get_all_symbols(self) -> list[str]: """Collects and returns all the symbols symbols currently defined in the model.""" # collect all symbols symbols = [variable.symbol for variable in self.variables] symbols += [objective.symbol for objective in self.objectives] if self.constants is not None: symbols += [constant.symbol for constant in self.constants] if self.constraints is not None: symbols += [constraint.symbol for constraint in self.constraints] if self.extra_funcs is not None: symbols += [extra.symbol for extra in self.extra_funcs] if self.scalarization_funcs is not None: symbols += [scalarization.symbol for scalarization in self.scalarization_funcs] return symbols def get_symbol_type_map(self) -> dict[str, str]: """Return a mapping of every named symbol to its element type. The type strings match the field names used in `Problem`: ``"variables"``, ``"constants"``, ``"objectives"``, ``"constraints"``, ``"extra_funcs"``, ``"scalarization_funcs"``. Scalarization functions with ``symbol=None`` are omitted. """ mapping: dict[str, str] = {} for v in self.variables: mapping[v.symbol] = "variables" for c in self.constants or []: mapping[c.symbol] = "constants" for o in self.objectives: mapping[o.symbol] = "objectives" for c in self.constraints or []: mapping[c.symbol] = "constraints" for f in self.extra_funcs or []: mapping[f.symbol] = "extra_funcs" for s in self.scalarization_funcs or []: if s.symbol is not None: mapping[s.symbol] = "scalarization_funcs" return mapping def add_scalarization(self, new_scal: ScalarizationFunction) -> "Problem": """Adds a new scalarization function to the model. If no symbol is defined, adds a name with the format 'scal_i'. Does not modify the original problem model, but instead returns a copy of it with the added scalarization function. Args: new_scal (ScalarizationFunction): Scalarization functions to be added to the model. Raises: ValueError: Raised when a ScalarizationFunction is given with a symbol that already exists in the model. Returns: Problem: a copy of the problem with the added scalarization function. """ if new_scal.symbol is None: new_scal.symbol = f"scal_{self._scalarization_index}" self._scalarization_index += 1 if self.scalarization_funcs is None: return self.model_copy(update={"scalarization_funcs": [new_scal]}) symbols = self.get_all_symbols() symbols.append(new_scal.symbol) symbol_counts = Counter(symbols) duplicates = {symbol: count for symbol, count in symbol_counts.items() if count > 1} if duplicates: msg = "Non-unique symbols found in the Problem model." for symbol, count in duplicates.items(): msg += f" Symbol '{symbol}' occurs {count} times." raise ValueError(msg) return self.model_copy(update={"scalarization_funcs": [*self.scalarization_funcs, new_scal]}) def update_ideal_and_nadir( self, new_ideal: dict[str, VariableType | None] | None = None, new_nadir: dict[str, VariableType | None] | None = None, ) -> "Problem": """Update the ideal and nadir values of the problem. Args: new_ideal (dict[str, VariableType | None] | None): _description_ new_nadir (dict[str, VariableType | None] | None): _description_ """ updated_objectives = [] for objective in self.objectives: new_objective = objective.model_copy( update={ **( {"ideal": new_ideal[objective.symbol]} if new_ideal is not None and objective.symbol in new_ideal else {} ), **( {"nadir": new_nadir[objective.symbol]} if new_nadir is not None and objective.symbol in new_nadir else {} ), } ) updated_objectives.append(new_objective) return self.model_copy(update={"objectives": updated_objectives}) def add_constraints(self, new_constraints: list[Constraint]) -> "Problem": """Adds new constraints to the problem model. Does not modify the original problem model, but instead returns a copy of it with the added constraints. The symbols of the new constraints to be added must be unique. Args: new_constraints (list[Constraint]): the new `Constraint`s to be added to the model. Raises: TypeError: when the `new_constraints` is not a list. ValueError: when duplicate symbols are found among the new_constraints, or any of the new constraints utilized an existing symbol in the problem's model. Returns: Problem: a copy of the problem with the added constraints. """ if not isinstance(new_constraints, list): # not a list msg = "The argument `new_constraints` must be a list." raise TypeError(msg) all_symbols = self.get_all_symbols() new_symbols = [const.symbol for const in new_constraints] if len(new_symbols) > len(set(new_symbols)): # duplicate symbols in the new constraint functions msg = "Duplicate symbols found in the new constraint functions to be added." raise ValueError(msg) for s in new_symbols: if s in all_symbols: # symbol already exists msg = "A symbol was provided for a new constraint that already exists in the problem definition." raise ValueError(msg) # proceed to add the new constraints return self.model_copy( update={ "constraints": new_constraints if self.constraints is None else [*self.constraints, *new_constraints] } ) def add_variables(self, new_variables: list[Variable | TensorVariable]) -> "Problem": """Adds new variables to the problem model. Does not modify the original problem model, but instead returns a copy of it with the added variables. The symbols of the new variables to be added must be unique. Args: new_variables (list[Variable | TensorVariable]): the new variables to be added to the model. Raises: TypeError: when the `new_variables` is not a list. ValueError: when duplicate symbols are found among the new_variables, or any of the new variables utilized an existing symbol in the problem's model. Returns: Problem: a copy of the problem with the added variables. """ if not isinstance(new_variables, list): # not a list msg = "The argument `new_variables` must be a list." raise TypeError(msg) all_symbols = self.get_all_symbols() new_symbols = [const.symbol for const in new_variables] if len(new_symbols) > len(set(new_symbols)): # duplicate symbols in the new variables msg = "Duplicate symbols found in the new variables to be added." raise ValueError(msg) for s in new_symbols: if s in all_symbols: # symbol already exists msg = "A symbol was provided for a new variable that already exists in the problem definition." raise ValueError(msg) # proceed to add the new variables, assumed existing variables are defined return self.model_copy(update={"variables": [*self.variables, *new_variables]}) def get_flattened_variables(self) -> list[Variable]: """Return a list of the (flattened) variables of the problem. Returns a list of the variables defined for the problem so that any TensorVariables are flattened. Returns: list[Variable]: list of (flattened) variables. """ return [ item for var in self.variables for item in (var.to_variables() if isinstance(var, TensorVariable) else [var]) ] def get_constraint(self, symbol: str) -> Constraint | None: """Return a copy of a `Constant` with the given symbol. Args: symbol (str): the symbol of the constraint. Returns: Constant | None: the copy of the constraint with the given symbol, or `None` if the constraint is not found. Also return `None` if no constraints have been defined for the problem. """ if self.constraints is None: # no constraints defined return None for constraint in self.constraints: if constraint.symbol == symbol: return constraint.model_copy() # did not find symbol return None def get_variable(self, symbol: str) -> Variable | TensorVariable | None: """Return a copy of a `Variable` with the given symbol. Args: symbol (str): the symbol of the variable. Returns: Variable | TensorVariable | None: the copy of the variable with the given symbol, or `None` if the variable is not found. """ for variable in self.variables: if variable.symbol == symbol: # variable found return variable.model_copy() # variable not found return None def get_objective(self, symbol: str, *, copy: bool = True) -> Objective | None: """Return a copy of an `Objective` with the given symbol. Args: symbol (str): the symbol of the objective. copy (bool): if True, return a copy of the objective, otherwise, return a reference. Defaults to True. Returns: Objective | None: the copy of the objective with the given symbol, or `None` if the objective is not found. """ for objective in self.objectives: if objective.symbol == symbol: # objective found if copy: # return a copy of the objective return objective.model_copy() # return a reference instead return objective # objective not found return None def get_scalarization(self, symbol: str) -> ScalarizationFunction | None: """Return a copy of a `ScalarizationFunction` with the given symbol. Args: symbol (str): the symbol of the scalarization function. Returns: ScalarizationFunction | None: the copy of the scalarization function with the given symbol, or `None` if the scalarization function is not found. Returns `None` also when no scalarization functions have been defined for the problem. """ if self.scalarization_funcs is None: # no scalarization functions defined return None for scal in self.scalarization_funcs: if scal.symbol == symbol: # scalarization function found return scal.model_copy() # scalarization function is not found return None def get_ideal_point(self) -> dict[str, float | None]: """Get the ideal point of the problem as an objective dict. Returns an objective dict containing the ideal values of the the problem for each objective function. These values may be `None`. Returns: dict[str, float | None]: an objective dict with the ideal point values (which may be `None`). """ return {f"{obj.symbol}": obj.ideal for obj in self.objectives} def get_nadir_point(self) -> dict[str, float | None]: """Get the nadir point of the problem as an objective dict. Returns an objective dict containing the nadir values of the the problem for each objective function. These values may be `None`. Returns: dict[str, float | None]: an objective dict with the nadir point values (which may be `None`). """ return {f"{obj.symbol}": obj.nadir for obj in self.objectives} @property def variable_domain(self) -> VariableDomainTypeEnum: """Check the variables defined for the problem and returns the type of their domain. Checks the variable types defined for the problem and tells if the problem is continuous, integer, binary, or mixed-integer. Returns: VariableDomainEnum: whether the problem is continuous, integer, binary, or mixed-integer. """ variable_types = [var.variable_type for var in self.variables] if all(t == VariableTypeEnum.real for t in variable_types): # all variables are real valued -> continuous problem return VariableDomainTypeEnum.continuous if all(t == VariableTypeEnum.binary for t in variable_types): # all variables are binary valued -> binary problem return VariableDomainTypeEnum.binary if all(t in [VariableTypeEnum.integer, VariableTypeEnum.binary] for t in variable_types): # all variables are integer or binary -> integer problem return VariableDomainTypeEnum.integer # mixed problem return VariableDomainTypeEnum.mixed @property def is_convex(self) -> bool: """Check if all the functions expressions in the problem are convex. Note: If the field "is_convex" is explicitly set, then the provided value is returned. Otherwise, this method just checks all the functions expressions present in the problem and return true if all of them are convex. For complicated problems, this might result in an incorrect results. User discretion is advised. Returns: bool: whether the problem is convex or not. """ if self.is_convex_ is not None: return self.is_convex_ is_convex_values = ( [obj.is_convex for obj in self.objectives] + ([con.is_convex for con in self.constraints] if self.constraints is not None else []) + ([extra.is_convex for extra in self.extra_funcs] if self.extra_funcs is not None else []) + ([scal.is_convex for scal in self.scalarization_funcs] if self.scalarization_funcs is not None else []) ) return all(is_convex_values) @property def is_linear(self) -> bool: """Check if all the functions expressions in the problem are linear. Note: If the field "is_linear" is explicitly set, then the provided value is returned. Otherwise, this method just checks all the functions expressions present in the problem and return true if all of them are linear. For complicated problems, this might result in an incorrect results. User discretion is advised. Returns: bool: whether the problem is linear or not. """ if self.is_linear_ is not None: return self.is_linear_ is_linear_values = ( [obj.is_linear for obj in self.objectives] + ([con.is_linear for con in self.constraints] if self.constraints is not None else []) + ([extra.is_linear for extra in self.extra_funcs] if self.extra_funcs is not None else []) + ([scal.is_linear for scal in self.scalarization_funcs] if self.scalarization_funcs is not None else []) ) return all(is_linear_values) @property def is_twice_differentiable(self) -> bool: """Check if all the functions expressions in the problem are twice differentiable. Note: If the field "is_twice_differentiable" is explicitly set, then the provided value is returned. Otherwise, this method just checks all the functions expressions present in the problem and return true if all of them are twice differentiable. For complicated problems, this might result in an incorrect results. User discretion is advised. Returns: bool: whether the problem is twice differentiable or not. """ if self.is_twice_differentiable_ is not None: return self.is_twice_differentiable_ is_diff_values = ( [obj.is_twice_differentiable for obj in self.objectives] + ([con.is_twice_differentiable for con in self.constraints] if self.constraints is not None else []) + ([extra.is_twice_differentiable for extra in self.extra_funcs] if self.extra_funcs is not None else []) + ( [scal.is_twice_differentiable for scal in self.scalarization_funcs] if self.scalarization_funcs is not None else [] ) ) return all(is_diff_values) def save_to_json(self, path: Path) -> None: """Save the Problem model in JSON format to a file. Args: path (Path): path to the file the model should be saved to. """ json_content = self.model_dump_json(indent=4) path.write_text(json_content, encoding="utf-8") @classmethod def load_json(cls, path: Path) -> "Problem": """Load a Problem model stored in a JSON file. Args: path (Path): path to file storing a Problem model in JSON format. Returns: Problem: the as defined in the data. """ json_data = path.read_text() return cls.model_validate_json(json_data, by_name=True) name: str = Field( description="Name of the problem.", ) """Name of the problem.""" description: str = Field(description="Description of the problem.") """Description of the problem.""" constants: list[Constant | TensorConstant] | None = Field( description="Optional list of the constants present in the problem.", default=None ) """List of the constants present in the problem. Defaults to `None`.""" variables: list[Variable | TensorVariable] = Field(description="List of variables present in the problem.") """List of variables present in the problem.""" objectives: list[Objective] = Field(description="List of the objectives present in the problem.") """List of the objectives present in the problem.""" constraints: list[Constraint] | None = Field( description="Optional list of constraints present in the problem.", default=None, ) """Optional list of constraints present in the problem. Defaults to `None`.""" extra_funcs: list[ExtraFunction] | None = Field( description="Optional list of extra functions. Use this if some function is repeated multiple times.", default=None, ) """Optional list of extra functions. Use this if some function is repeated multiple times. Defaults to `None`.""" scalarization_funcs: list[ScalarizationFunction] | None = Field( description="Optional list of scalarization functions of the problem.", default=None ) """Optional list of scalarization functions of the problem. Defaults to `None`.""" discrete_representation: DiscreteRepresentation | None = Field( description=( "Optional. Required when there are one or more 'data_based' Objectives. The corresponding values " "of the 'data_based' objective function will be fetched from this with the given variable values. " "Is also utilized for methods which require both an analytical and discrete representation of a problem." ), default=None, ) """Optional. Required when there are one or more 'data_based' Objectives. The corresponding values of the 'data_based' objective function will be fetched from this with the given variable values. Is also utilized for methods which require both an analytical and discrete representation of a problem. Defaults to `None`.""" simulators: list[Simulator] | None = Field( description=( "Optional. The simulators used by the problem. Required when there are one or more " "Objectives defined by simulators. The corresponding values of the 'simulator' objective " "function will be fetched from these simulators with the given variable values." ), default=None, ) """Optional. The simulators used by the problem. Required when there are one or more Objectives defined by simulators. The corresponding values of the 'simulator' objective function will be fetched from these simulators with the given variable values. Defaults to `None`.""" is_convex_: bool | None = Field( description=( "Optional. Used to manually indicate if the problem, as a whole, can be considered to be convex. " "If set to `None`, this property will be automatically inferred from the " "respective properties of other attributes." ), default=None, alias="is_convex", ) """Optional. Used to manually indicate if the problem, as a whole, can be considered to be convex. " "If set to `None`, this property will be automatically inferred from the " "respective properties of other attributes.""" is_linear_: bool | None = Field( description=( "Optional. Used to manually indicate if the problem, as a whole, can be considered to be linear. " "If set to `None`, this property will be automatically inferred from the " "respective properties of other attributes." ), default=None, alias="is_linear", ) """Optional. Used to manually indicate if the problem, as a whole, can be considered to be linear. " "If set to `None`, this property will be automatically inferred from the " "respective properties of other attributes.""" is_twice_differentiable_: bool | None = Field( description=( "Optional. Used to manually indicate if the problem, as a whole, can be considered to be twice " "differentiable. If set to `None`, this property will be automatically inferred from the " "respective properties of other attributes." ), default=None, alias="is_twice_differentiable", ) """Optional. Used to manually indicate if the problem, as a whole, can be considered to be twice " "differentiable. If set to `None`, this property will be automatically inferred from the " "respective properties of other attributes.""" ``` ##### constants ``` constants: list[Constant | TensorConstant] | None = Field( description="Optional list of the constants present in the problem.", default=None, ) ``` List of the constants present in the problem. Defaults to `None`. ##### constraints ``` constraints: list[Constraint] | None = Field( description="Optional list of constraints present in the problem.", default=None, ) ``` Optional list of constraints present in the problem. Defaults to `None`. ##### description ``` description: str = Field( description="Description of the problem." ) ``` Description of the problem. ##### discrete_representation ``` discrete_representation: DiscreteRepresentation | None = ( Field( description="Optional. Required when there are one or more 'data_based' Objectives. The corresponding values of the 'data_based' objective function will be fetched from this with the given variable values. Is also utilized for methods which require both an analytical and discrete representation of a problem.", default=None, ) ) ``` Optional. Required when there are one or more 'data_based' Objectives. The corresponding values of the 'data_based' objective function will be fetched from this with the given variable values. Is also utilized for methods which require both an analytical and discrete representation of a problem. Defaults to `None`. ##### extra_funcs ``` extra_funcs: list[ExtraFunction] | None = Field( description="Optional list of extra functions. Use this if some function is repeated multiple times.", default=None, ) ``` Optional list of extra functions. Use this if some function is repeated multiple times. Defaults to `None`. ##### is_convex ``` is_convex: bool ``` Check if all the functions expressions in the problem are convex. Note If the field "is_convex" is explicitly set, then the provided value is returned. Otherwise, this method just checks all the functions expressions present in the problem and return true if all of them are convex. For complicated problems, this might result in an incorrect results. User discretion is advised. Returns: | Name | Type | Description | | ------ | ------ | ------------------------------------- | | `bool` | `bool` | whether the problem is convex or not. | ##### is_convex\_ ``` is_convex_: bool | None = Field( description="Optional. Used to manually indicate if the problem, as a whole, can be considered to be convex. If set to `None`, this property will be automatically inferred from the respective properties of other attributes.", default=None, alias="is_convex", ) ``` Optional. Used to manually indicate if the problem, as a whole, can be considered to be convex. " "If set to `None`, this property will be automatically inferred from the " "respective properties of other attributes. ##### is_linear ``` is_linear: bool ``` Check if all the functions expressions in the problem are linear. Note If the field "is_linear" is explicitly set, then the provided value is returned. Otherwise, this method just checks all the functions expressions present in the problem and return true if all of them are linear. For complicated problems, this might result in an incorrect results. User discretion is advised. Returns: | Name | Type | Description | | ------ | ------ | ------------------------------------- | | `bool` | `bool` | whether the problem is linear or not. | ##### is_linear\_ ``` is_linear_: bool | None = Field( description="Optional. Used to manually indicate if the problem, as a whole, can be considered to be linear. If set to `None`, this property will be automatically inferred from the respective properties of other attributes.", default=None, alias="is_linear", ) ``` Optional. Used to manually indicate if the problem, as a whole, can be considered to be linear. " "If set to `None`, this property will be automatically inferred from the " "respective properties of other attributes. ##### is_twice_differentiable ``` is_twice_differentiable: bool ``` Check if all the functions expressions in the problem are twice differentiable. Note If the field "is_twice_differentiable" is explicitly set, then the provided value is returned. Otherwise, this method just checks all the functions expressions present in the problem and return true if all of them are twice differentiable. For complicated problems, this might result in an incorrect results. User discretion is advised. Returns: | Name | Type | Description | | ------ | ------ | --------------------------------------------------- | | `bool` | `bool` | whether the problem is twice differentiable or not. | ##### is_twice_differentiable\_ ``` is_twice_differentiable_: bool | None = Field( description="Optional. Used to manually indicate if the problem, as a whole, can be considered to be twice differentiable. If set to `None`, this property will be automatically inferred from the respective properties of other attributes.", default=None, alias="is_twice_differentiable", ) ``` Optional. Used to manually indicate if the problem, as a whole, can be considered to be twice " "differentiable. If set to `None`, this property will be automatically inferred from the " "respective properties of other attributes. ##### name ``` name: str = Field(description='Name of the problem.') ``` Name of the problem. ##### objectives ``` objectives: list[Objective] = Field( description="List of the objectives present in the problem." ) ``` List of the objectives present in the problem. ##### scalarization_funcs ``` scalarization_funcs: list[ScalarizationFunction] | None = ( Field( description="Optional list of scalarization functions of the problem.", default=None, ) ) ``` Optional list of scalarization functions of the problem. Defaults to `None`. ##### simulators ``` simulators: list[Simulator] | None = Field( description="Optional. The simulators used by the problem. Required when there are one or more Objectives defined by simulators. The corresponding values of the 'simulator' objective function will be fetched from these simulators with the given variable values.", default=None, ) ``` Optional. The simulators used by the problem. Required when there are one or more Objectives defined by simulators. The corresponding values of the 'simulator' objective function will be fetched from these simulators with the given variable values. Defaults to `None`. ##### variable_domain ``` variable_domain: VariableDomainTypeEnum ``` Check the variables defined for the problem and returns the type of their domain. Checks the variable types defined for the problem and tells if the problem is continuous, integer, binary, or mixed-integer. Returns: | Name | Type | Description | | -------------------- | ------------------------ | --------------------------------------------------------------------- | | `VariableDomainEnum` | `VariableDomainTypeEnum` | whether the problem is continuous, integer, binary, or mixed-integer. | ##### variables ``` variables: list[Variable | TensorVariable] = Field( description="List of variables present in the problem." ) ``` List of variables present in the problem. ##### add_constraints ``` add_constraints( new_constraints: list[Constraint], ) -> Problem ``` Adds new constraints to the problem model. Does not modify the original problem model, but instead returns a copy of it with the added constraints. The symbols of the new constraints to be added must be unique. Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | --------------------------------------------- | ---------- | | `new_constraints` | `list[Constraint]` | the new Constraints to be added to the model. | *required* | Raises: | Type | Description | | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | | `TypeError` | when the new_constraints is not a list. | | `ValueError` | when duplicate symbols are found among the new_constraints, or any of the new constraints utilized an existing symbol in the problem's model. | Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------- | | `Problem` | `Problem` | a copy of the problem with the added constraints. | Source code in `desdeo/problem/schema.py` ``` def add_constraints(self, new_constraints: list[Constraint]) -> "Problem": """Adds new constraints to the problem model. Does not modify the original problem model, but instead returns a copy of it with the added constraints. The symbols of the new constraints to be added must be unique. Args: new_constraints (list[Constraint]): the new `Constraint`s to be added to the model. Raises: TypeError: when the `new_constraints` is not a list. ValueError: when duplicate symbols are found among the new_constraints, or any of the new constraints utilized an existing symbol in the problem's model. Returns: Problem: a copy of the problem with the added constraints. """ if not isinstance(new_constraints, list): # not a list msg = "The argument `new_constraints` must be a list." raise TypeError(msg) all_symbols = self.get_all_symbols() new_symbols = [const.symbol for const in new_constraints] if len(new_symbols) > len(set(new_symbols)): # duplicate symbols in the new constraint functions msg = "Duplicate symbols found in the new constraint functions to be added." raise ValueError(msg) for s in new_symbols: if s in all_symbols: # symbol already exists msg = "A symbol was provided for a new constraint that already exists in the problem definition." raise ValueError(msg) # proceed to add the new constraints return self.model_copy( update={ "constraints": new_constraints if self.constraints is None else [*self.constraints, *new_constraints] } ) ``` ##### add_scalarization ``` add_scalarization( new_scal: ScalarizationFunction, ) -> Problem ``` Adds a new scalarization function to the model. If no symbol is defined, adds a name with the format 'scal_i'. Does not modify the original problem model, but instead returns a copy of it with the added scalarization function. Parameters: | Name | Type | Description | Default | | ---------- | ----------------------- | ------------------------------------------------- | ---------- | | `new_scal` | `ScalarizationFunction` | Scalarization functions to be added to the model. | *required* | Raises: | Type | Description | | ------------ | -------------------------------------------------------------------------------------------- | | `ValueError` | Raised when a ScalarizationFunction is given with a symbol that already exists in the model. | Returns: | Name | Type | Description | | --------- | --------- | ------------------------------------------------------------ | | `Problem` | `Problem` | a copy of the problem with the added scalarization function. | Source code in `desdeo/problem/schema.py` ``` def add_scalarization(self, new_scal: ScalarizationFunction) -> "Problem": """Adds a new scalarization function to the model. If no symbol is defined, adds a name with the format 'scal_i'. Does not modify the original problem model, but instead returns a copy of it with the added scalarization function. Args: new_scal (ScalarizationFunction): Scalarization functions to be added to the model. Raises: ValueError: Raised when a ScalarizationFunction is given with a symbol that already exists in the model. Returns: Problem: a copy of the problem with the added scalarization function. """ if new_scal.symbol is None: new_scal.symbol = f"scal_{self._scalarization_index}" self._scalarization_index += 1 if self.scalarization_funcs is None: return self.model_copy(update={"scalarization_funcs": [new_scal]}) symbols = self.get_all_symbols() symbols.append(new_scal.symbol) symbol_counts = Counter(symbols) duplicates = {symbol: count for symbol, count in symbol_counts.items() if count > 1} if duplicates: msg = "Non-unique symbols found in the Problem model." for symbol, count in duplicates.items(): msg += f" Symbol '{symbol}' occurs {count} times." raise ValueError(msg) return self.model_copy(update={"scalarization_funcs": [*self.scalarization_funcs, new_scal]}) ``` ##### add_variables ``` add_variables( new_variables: list[Variable | TensorVariable], ) -> Problem ``` Adds new variables to the problem model. Does not modify the original problem model, but instead returns a copy of it with the added variables. The symbols of the new variables to be added must be unique. Parameters: | Name | Type | Description | Default | | --------------- | ---------------- | ------------------ | ------------------------------------------- | | `new_variables` | \`list\[Variable | TensorVariable\]\` | the new variables to be added to the model. | Raises: | Type | Description | | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | | `TypeError` | when the new_variables is not a list. | | `ValueError` | when duplicate symbols are found among the new_variables, or any of the new variables utilized an existing symbol in the problem's model. | Returns: | Name | Type | Description | | --------- | --------- | ----------------------------------------------- | | `Problem` | `Problem` | a copy of the problem with the added variables. | Source code in `desdeo/problem/schema.py` ``` def add_variables(self, new_variables: list[Variable | TensorVariable]) -> "Problem": """Adds new variables to the problem model. Does not modify the original problem model, but instead returns a copy of it with the added variables. The symbols of the new variables to be added must be unique. Args: new_variables (list[Variable | TensorVariable]): the new variables to be added to the model. Raises: TypeError: when the `new_variables` is not a list. ValueError: when duplicate symbols are found among the new_variables, or any of the new variables utilized an existing symbol in the problem's model. Returns: Problem: a copy of the problem with the added variables. """ if not isinstance(new_variables, list): # not a list msg = "The argument `new_variables` must be a list." raise TypeError(msg) all_symbols = self.get_all_symbols() new_symbols = [const.symbol for const in new_variables] if len(new_symbols) > len(set(new_symbols)): # duplicate symbols in the new variables msg = "Duplicate symbols found in the new variables to be added." raise ValueError(msg) for s in new_symbols: if s in all_symbols: # symbol already exists msg = "A symbol was provided for a new variable that already exists in the problem definition." raise ValueError(msg) # proceed to add the new variables, assumed existing variables are defined return self.model_copy(update={"variables": [*self.variables, *new_variables]}) ``` ##### check_for_non_unique_symbols ``` check_for_non_unique_symbols() -> Problem ``` Check that all the symbols defined in the different fields are unique. Source code in `desdeo/problem/schema.py` ``` @model_validator(mode="after") def check_for_non_unique_symbols(self) -> "Problem": """Check that all the symbols defined in the different fields are unique.""" symbols = self.get_all_symbols() # symbol is always populated symbol_counts = Counter(symbols) # collect duplicates, if they exist duplicates = {symbol: count for symbol, count in symbol_counts.items() if count > 1} if duplicates: # if any duplicates are found, raise a value error and report the duplicate symbols. msg = "Non-unique symbols found in the Problem model." for symbol, count in duplicates.items(): msg += f" Symbol '{symbol}' occurs {count} times." raise ValueError(msg) return self ``` ##### from_problemdb ``` from_problemdb(db_instance: ProblemDB) -> Problem ``` . Source code in `desdeo/problem/schema.py` ``` @classmethod def from_problemdb(cls, db_instance: "ProblemDB") -> "Problem": """.""" constants = [Constant.model_validate(const) for const in db_instance.constants] + [ TensorConstant.model_validate(const) for const in db_instance.tensor_constants ] return cls( name=db_instance.name, description=db_instance.description, is_convex=db_instance.is_convex, is_linear=db_instance.is_linear, is_twice_differentiable=db_instance.is_twice_differentiable, constants=constants if constants != [] else None, variables=[Variable.model_validate(var) for var in db_instance.variables] + [TensorVariable.model_validate(var) for var in db_instance.tensor_variables], objectives=[Objective.model_validate(obj) for obj in db_instance.objectives], constraints=[Constraint.model_validate(const) for const in db_instance.constraints] if db_instance.constraints != [] else None, scalarization_funcs=[ScalarizationFunction.model_validate(scal) for scal in db_instance.scalarization_funcs] if db_instance.scalarization_funcs != [] else None, extra_funcs=[ExtraFunction.model_validate(extra) for extra in db_instance.extra_funcs] if db_instance.extra_funcs != [] else None, discrete_representation=DiscreteRepresentation.model_validate(db_instance.discrete_representation) if db_instance.discrete_representation is not None else None, simulators=[Simulator.model_validate(sim) for sim in db_instance.simulators] if db_instance.simulators != [] else None, ) ``` ##### get_all_symbols ``` get_all_symbols() -> list[str] ``` Collects and returns all the symbols symbols currently defined in the model. Source code in `desdeo/problem/schema.py` ``` def get_all_symbols(self) -> list[str]: """Collects and returns all the symbols symbols currently defined in the model.""" # collect all symbols symbols = [variable.symbol for variable in self.variables] symbols += [objective.symbol for objective in self.objectives] if self.constants is not None: symbols += [constant.symbol for constant in self.constants] if self.constraints is not None: symbols += [constraint.symbol for constraint in self.constraints] if self.extra_funcs is not None: symbols += [extra.symbol for extra in self.extra_funcs] if self.scalarization_funcs is not None: symbols += [scalarization.symbol for scalarization in self.scalarization_funcs] return symbols ``` ##### get_constraint ``` get_constraint(symbol: str) -> Constraint | None ``` Return a copy of a `Constant` with the given symbol. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------- | ---------- | | `symbol` | `str` | the symbol of the constraint. | *required* | Returns: | Type | Description | | ------------ | ----------- | | \`Constraint | None\` | Source code in `desdeo/problem/schema.py` ``` def get_constraint(self, symbol: str) -> Constraint | None: """Return a copy of a `Constant` with the given symbol. Args: symbol (str): the symbol of the constraint. Returns: Constant | None: the copy of the constraint with the given symbol, or `None` if the constraint is not found. Also return `None` if no constraints have been defined for the problem. """ if self.constraints is None: # no constraints defined return None for constraint in self.constraints: if constraint.symbol == symbol: return constraint.model_copy() # did not find symbol return None ``` ##### get_flattened_variables ``` get_flattened_variables() -> list[Variable] ``` Return a list of the (flattened) variables of the problem. Returns a list of the variables defined for the problem so that any TensorVariables are flattened. Returns: | Type | Description | | ---------------- | ------------------------------------------------ | | `list[Variable]` | list\[Variable\]: list of (flattened) variables. | Source code in `desdeo/problem/schema.py` ``` def get_flattened_variables(self) -> list[Variable]: """Return a list of the (flattened) variables of the problem. Returns a list of the variables defined for the problem so that any TensorVariables are flattened. Returns: list[Variable]: list of (flattened) variables. """ return [ item for var in self.variables for item in (var.to_variables() if isinstance(var, TensorVariable) else [var]) ] ``` ##### get_ideal_point ``` get_ideal_point() -> dict[str, float | None] ``` Get the ideal point of the problem as an objective dict. Returns an objective dict containing the ideal values of the the problem for each objective function. These values may be `None`. Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | None\]\` | Source code in `desdeo/problem/schema.py` ``` def get_ideal_point(self) -> dict[str, float | None]: """Get the ideal point of the problem as an objective dict. Returns an objective dict containing the ideal values of the the problem for each objective function. These values may be `None`. Returns: dict[str, float | None]: an objective dict with the ideal point values (which may be `None`). """ return {f"{obj.symbol}": obj.ideal for obj in self.objectives} ``` ##### get_nadir_point ``` get_nadir_point() -> dict[str, float | None] ``` Get the nadir point of the problem as an objective dict. Returns an objective dict containing the nadir values of the the problem for each objective function. These values may be `None`. Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | None\]\` | Source code in `desdeo/problem/schema.py` ``` def get_nadir_point(self) -> dict[str, float | None]: """Get the nadir point of the problem as an objective dict. Returns an objective dict containing the nadir values of the the problem for each objective function. These values may be `None`. Returns: dict[str, float | None]: an objective dict with the nadir point values (which may be `None`). """ return {f"{obj.symbol}": obj.nadir for obj in self.objectives} ``` ##### get_objective ``` get_objective( symbol: str, *, copy: bool = True ) -> Objective | None ``` Return a copy of an `Objective` with the given symbol. Parameters: | Name | Type | Description | Default | | -------- | ------ | ----------------------------------------------------------------------------------------- | ---------- | | `symbol` | `str` | the symbol of the objective. | *required* | | `copy` | `bool` | if True, return a copy of the objective, otherwise, return a reference. Defaults to True. | `True` | Returns: | Type | Description | | ----------- | ----------- | | \`Objective | None\` | Source code in `desdeo/problem/schema.py` ``` def get_objective(self, symbol: str, *, copy: bool = True) -> Objective | None: """Return a copy of an `Objective` with the given symbol. Args: symbol (str): the symbol of the objective. copy (bool): if True, return a copy of the objective, otherwise, return a reference. Defaults to True. Returns: Objective | None: the copy of the objective with the given symbol, or `None` if the objective is not found. """ for objective in self.objectives: if objective.symbol == symbol: # objective found if copy: # return a copy of the objective return objective.model_copy() # return a reference instead return objective # objective not found return None ``` ##### get_scalarization ``` get_scalarization( symbol: str, ) -> ScalarizationFunction | None ``` Return a copy of a `ScalarizationFunction` with the given symbol. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------- | ---------- | | `symbol` | `str` | the symbol of the scalarization function. | *required* | Returns: | Type | Description | | ----------------------- | ----------- | | \`ScalarizationFunction | None\` | Source code in `desdeo/problem/schema.py` ``` def get_scalarization(self, symbol: str) -> ScalarizationFunction | None: """Return a copy of a `ScalarizationFunction` with the given symbol. Args: symbol (str): the symbol of the scalarization function. Returns: ScalarizationFunction | None: the copy of the scalarization function with the given symbol, or `None` if the scalarization function is not found. Returns `None` also when no scalarization functions have been defined for the problem. """ if self.scalarization_funcs is None: # no scalarization functions defined return None for scal in self.scalarization_funcs: if scal.symbol == symbol: # scalarization function found return scal.model_copy() # scalarization function is not found return None ``` ##### get_symbol_type_map ``` get_symbol_type_map() -> dict[str, str] ``` Return a mapping of every named symbol to its element type. The type strings match the field names used in `Problem`: `"variables"`, `"constants"`, `"objectives"`, `"constraints"`, `"extra_funcs"`, `"scalarization_funcs"`. Scalarization functions with `symbol=None` are omitted. Source code in `desdeo/problem/schema.py` ``` def get_symbol_type_map(self) -> dict[str, str]: """Return a mapping of every named symbol to its element type. The type strings match the field names used in `Problem`: ``"variables"``, ``"constants"``, ``"objectives"``, ``"constraints"``, ``"extra_funcs"``, ``"scalarization_funcs"``. Scalarization functions with ``symbol=None`` are omitted. """ mapping: dict[str, str] = {} for v in self.variables: mapping[v.symbol] = "variables" for c in self.constants or []: mapping[c.symbol] = "constants" for o in self.objectives: mapping[o.symbol] = "objectives" for c in self.constraints or []: mapping[c.symbol] = "constraints" for f in self.extra_funcs or []: mapping[f.symbol] = "extra_funcs" for s in self.scalarization_funcs or []: if s.symbol is not None: mapping[s.symbol] = "scalarization_funcs" return mapping ``` ##### get_variable ``` get_variable( symbol: str, ) -> Variable | TensorVariable | None ``` Return a copy of a `Variable` with the given symbol. Parameters: | Name | Type | Description | Default | | -------- | ----- | --------------------------- | ---------- | | `symbol` | `str` | the symbol of the variable. | *required* | Returns: | Type | Description | | ---------- | -------------- | | \`Variable | TensorVariable | Source code in `desdeo/problem/schema.py` ``` def get_variable(self, symbol: str) -> Variable | TensorVariable | None: """Return a copy of a `Variable` with the given symbol. Args: symbol (str): the symbol of the variable. Returns: Variable | TensorVariable | None: the copy of the variable with the given symbol, or `None` if the variable is not found. """ for variable in self.variables: if variable.symbol == symbol: # variable found return variable.model_copy() # variable not found return None ``` ##### load_json ``` load_json(path: Path) -> Problem ``` Load a Problem model stored in a JSON file. Parameters: | Name | Type | Description | Default | | ------ | ------ | ---------------------------------------------------- | ---------- | | `path` | `Path` | path to file storing a Problem model in JSON format. | *required* | Returns: | Name | Type | Description | | --------- | --------- | --------------------------- | | `Problem` | `Problem` | the as defined in the data. | Source code in `desdeo/problem/schema.py` ``` @classmethod def load_json(cls, path: Path) -> "Problem": """Load a Problem model stored in a JSON file. Args: path (Path): path to file storing a Problem model in JSON format. Returns: Problem: the as defined in the data. """ json_data = path.read_text() return cls.model_validate_json(json_data, by_name=True) ``` ##### save_to_json ``` save_to_json(path: Path) -> None ``` Save the Problem model in JSON format to a file. Parameters: | Name | Type | Description | Default | | ------ | ------ | ---------------------------------------------- | ---------- | | `path` | `Path` | path to the file the model should be saved to. | *required* | Source code in `desdeo/problem/schema.py` ``` def save_to_json(self, path: Path) -> None: """Save the Problem model in JSON format to a file. Args: path (Path): path to the file the model should be saved to. """ json_content = self.model_dump_json(indent=4) path.write_text(json_content, encoding="utf-8") ``` ##### set_default_scalarization_names ``` set_default_scalarization_names() -> Problem ``` Check the scalarization functions for symbols with value 'None'. If found, names them systematically 'scal_i', where 'i' is a running index stored in an instance attribute. Source code in `desdeo/problem/schema.py` ``` @model_validator(mode="after") def set_default_scalarization_names(self) -> "Problem": """Check the scalarization functions for symbols with value 'None'. If found, names them systematically 'scal_i', where 'i' is a running index stored in an instance attribute. """ if self.scalarization_funcs is None: return self for func in self.scalarization_funcs: if func.symbol is None: func.symbol = f"scal_{self._scalarization_index}" self._scalarization_index += 1 return self ``` ##### update_ideal_and_nadir ``` update_ideal_and_nadir( new_ideal: dict[str, VariableType | None] | None = None, new_nadir: dict[str, VariableType | None] | None = None, ) -> Problem ``` Update the ideal and nadir values of the problem. Parameters: | Name | Type | Description | Default | | ----------- | ------------------------- | ----------- | ------- | | `new_ideal` | \`dict\[str, VariableType | None\] | None\` | | `new_nadir` | \`dict\[str, VariableType | None\] | None\` | Source code in `desdeo/problem/schema.py` ``` def update_ideal_and_nadir( self, new_ideal: dict[str, VariableType | None] | None = None, new_nadir: dict[str, VariableType | None] | None = None, ) -> "Problem": """Update the ideal and nadir values of the problem. Args: new_ideal (dict[str, VariableType | None] | None): _description_ new_nadir (dict[str, VariableType | None] | None): _description_ """ updated_objectives = [] for objective in self.objectives: new_objective = objective.model_copy( update={ **( {"ideal": new_ideal[objective.symbol]} if new_ideal is not None and objective.symbol in new_ideal else {} ), **( {"nadir": new_nadir[objective.symbol]} if new_nadir is not None and objective.symbol in new_nadir else {} ), } ) updated_objectives.append(new_objective) return self.model_copy(update={"objectives": updated_objectives}) ``` #### ScalarizationFunction Bases: `BaseModel` Model for scalarization of the problem. Source code in `desdeo/problem/schema.py` ``` class ScalarizationFunction(BaseModel): """Model for scalarization of the problem.""" model_config = ConfigDict(from_attributes=True, extra="forbid") name: str = Field(description=("Name of the scalarization function.")) """Name of the scalarization function.""" symbol: str | None = Field( description=( "Optional symbol to represent the scalarization function. This may be used in UIs and visualizations." ), default=None, ) """Optional symbol to represent the scalarization function. This may be used in UIs and visualizations. Defaults to `None`.""" func: list = Field( description=( "Function representation of the scalarization. This is a JSON object that can be parsed into a function." "Must be a valid MathJSON object." " The symbols in the function must match the symbols defined for objective/variable/constant/extra" " function." ), ) """ Function representation of the scalarization. This is a JSON object that can be parsed into a function. Must be a valid MathJSON object. The symbols in the function must match the symbols defined for objective/variable/constant/extra function.""" is_linear: bool = Field( description="Whether the function expression is linear or not. Defaults to `False`.", default=False ) """Whether the function expression is linear or not. Defaults to `False`.""" is_convex: bool = Field( description="Whether the function expression is convex or not (non-convex). Defaults to `False`.", default=False, ) """Whether the function expression is convex or not (non-convex). Defaults to `False`.""" is_twice_differentiable: bool = Field( description="Whether the function expression is twice differentiable or not. Defaults to `False`", default=False, ) """Whether the function expression is twice differentiable or not. Defaults to `False`""" _parse_infix_to_func = field_validator("func", mode="before")(parse_infix_to_func) ``` ##### func ``` func: list = Field( description="Function representation of the scalarization. This is a JSON object that can be parsed into a function.Must be a valid MathJSON object. The symbols in the function must match the symbols defined for objective/variable/constant/extra function." ) ``` Function representation of the scalarization. This is a JSON object that can be parsed into a function. Must be a valid MathJSON object. The symbols in the function must match the symbols defined for objective/variable/constant/extra function. ##### is_convex ``` is_convex: bool = Field( description="Whether the function expression is convex or not (non-convex). Defaults to `False`.", default=False, ) ``` Whether the function expression is convex or not (non-convex). Defaults to `False`. ##### is_linear ``` is_linear: bool = Field( description="Whether the function expression is linear or not. Defaults to `False`.", default=False, ) ``` Whether the function expression is linear or not. Defaults to `False`. ##### is_twice_differentiable ``` is_twice_differentiable: bool = Field( description="Whether the function expression is twice differentiable or not. Defaults to `False`", default=False, ) ``` Whether the function expression is twice differentiable or not. Defaults to `False` ##### name ``` name: str = Field( description="Name of the scalarization function." ) ``` Name of the scalarization function. ##### symbol ``` symbol: str | None = Field( description="Optional symbol to represent the scalarization function. This may be used in UIs and visualizations.", default=None, ) ``` Optional symbol to represent the scalarization function. This may be used in UIs and visualizations. Defaults to `None`. #### Simulator Bases: `BaseModel` Model for simulator data. One of `file` or `url` must be provided, but not both. Source code in `desdeo/problem/schema.py` ``` class Simulator(BaseModel): """Model for simulator data. One of `file` or `url` must be provided, but not both. """ model_config = ConfigDict(frozen=True, from_attributes=True, extra="forbid") name: str = Field( description=("Descriptive name of the simulator. This can be used in UI and visualizations."), ) """Descriptive name of the simulator. This can be used in UI and visualizations.""" symbol: str = Field( description=( "Symbol to represent the simulator. This will be used in the rest of the problem definition." " It may also be used in UIs and visualizations." ), ) file: Path | None = Field(description=("Path to a python file with the connection to simulators."), default=None) """Path to a python file with the connection to simulators.""" url: Url | None = Field( description=( "Optional. URL to the simulator. A GET request to this URL should be used to evaluate solutions in batches." ), default=None, ) """Optional. A URL to the simulator. A GET request to this URL should be used to evaluate solutions in batches.""" parameter_options: dict | None = Field( description=( "Parameters to the simulator that are not decision variables, but affect the results." "Format is similar to decision variables. Can be 'None'." ), default=None, ) """Parameters to the simulator that are not decision variables, but affect the results. Format is similar to decision variables. Can be 'None'.""" # Check that either file or url is provided, but not both @model_validator(mode="after") def check_file_or_url(self) -> Self: """Ensure that either file or url is provided, but not both.""" if self.file is None and self.url is None: raise ValueError("Either 'file' or 'url' must be provided.") if self.file is not None and self.url is not None: raise ValueError("Only one of 'file' or 'url' can be provided.") return self ``` ##### file ``` file: Path | None = Field( description="Path to a python file with the connection to simulators.", default=None, ) ``` Path to a python file with the connection to simulators. ##### name ``` name: str = Field( description="Descriptive name of the simulator. This can be used in UI and visualizations." ) ``` Descriptive name of the simulator. This can be used in UI and visualizations. ##### parameter_options ``` parameter_options: dict | None = Field( description="Parameters to the simulator that are not decision variables, but affect the results.Format is similar to decision variables. Can be 'None'.", default=None, ) ``` Parameters to the simulator that are not decision variables, but affect the results. Format is similar to decision variables. Can be 'None'. ##### url ``` url: Url | None = Field( description="Optional. URL to the simulator. A GET request to this URL should be used to evaluate solutions in batches.", default=None, ) ``` Optional. A URL to the simulator. A GET request to this URL should be used to evaluate solutions in batches. ##### check_file_or_url ``` check_file_or_url() -> Self ``` Ensure that either file or url is provided, but not both. Source code in `desdeo/problem/schema.py` ``` @model_validator(mode="after") def check_file_or_url(self) -> Self: """Ensure that either file or url is provided, but not both.""" if self.file is None and self.url is None: raise ValueError("Either 'file' or 'url' must be provided.") if self.file is not None and self.url is not None: raise ValueError("Only one of 'file' or 'url' can be provided.") return self ``` #### TensorConstant Bases: `BaseModel` Model for a tensor containing constant values. Source code in `desdeo/problem/schema.py` ``` class TensorConstant(BaseModel): """Model for a tensor containing constant values.""" model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True, from_attributes=True, extra="forbid") name: str = Field(description="Descriptive name of the tensor representing the values. E.g., 'distances'") """Descriptive name of the tensor representing the values. E.g., 'distances'""" symbol: str = Field( description=( "Symbol to represent the constant. This will be used in the rest of the problem definition." " Notice that the elements of the tensor will be represented with the symbol followed by" " indices. E.g., the first element of the third element of a 2-dimensional tensor," " is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable." " Note that indexing starts from 1." ) ) """ Symbol to represent the constant. This will be used in the rest of the problem definition. Notice that the elements of the tensor will be represented with the symbol followed by indices. E.g., the first element of the third element of a 2-dimensional tensor, is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable. Note that indexing starts from 1. """ shape: list[int] = Field( description=( "A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns." ) ) """A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns. """ values: Tensor = Field( description=( "A list of lists, with the elements representing the values of each constant element in the tensor. " "E.g., `[[5, 22, 0], [14, 5, 44]]`." ), ) """A list of lists, with the elements representing the initial values of each constant element in the tensor. E.g., `[[5, 22, 0], [14, 5, 44]]`.""" _parse_list_to_mathjson = field_validator("values", mode="before")(parse_list_to_mathjson) def get_values(self) -> Iterable[VariableType | Iterable[VariableType]] | Iterable[None, Iterable[None]]: """Return the constant values as a Python iterable (e.g., list of list).""" values = get_tensor_values(self.values) if isinstance(values, VariableType | None): return np.full(self.shape, values).tolist() return values def to_constants(self) -> list[Constant]: """Flatten the tensor into a list of Constants. Returns: list[Constant]: a list of Constants. """ constants = [] for indices in list(product(*[range(1, dim + 1) for dim in self.shape])): constants.append(self[*indices]) return constants def __getitem__(self, indices: int | tuple[int]) -> Constant: """Implements random access for TensorConstant. Note: Indexing is assumed to start at 1. Args: indices (int | Tuple[int]): a single integer or tuple of integers. Returns: Constant: A new instance of Constant that has been setup with information found at the specified indices in the TensorConstant. """ if isinstance(indices, tuple): # multi-dimensional indexing name = f"{self.name} at position {[*indices]}" symbol = f"{self.symbol}_{'_'.join(map(str, indices))}" value = self.get_values() for idx in indices: value = value[idx - 1] else: # single indexing name = f"{self.name} at position [{indices}]" symbol = f"{self.symbol}_{indices}" value = self.get_values()[indices - 1] return Constant(name=name, symbol=symbol, value=value) ``` ##### name ``` name: str = Field( description="Descriptive name of the tensor representing the values. E.g., 'distances'" ) ``` Descriptive name of the tensor representing the values. E.g., 'distances' ##### shape ``` shape: list[int] = Field( description="A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns." ) ``` A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns. ##### symbol ``` symbol: str = Field( description="Symbol to represent the constant. This will be used in the rest of the problem definition. Notice that the elements of the tensor will be represented with the symbol followed by indices. E.g., the first element of the third element of a 2-dimensional tensor, is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable. Note that indexing starts from 1." ) ``` Symbol to represent the constant. This will be used in the rest of the problem definition. Notice that the elements of the tensor will be represented with the symbol followed by indices. E.g., the first element of the third element of a 2-dimensional tensor, is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable. Note that indexing starts from 1. ##### values ``` values: Tensor = Field( description="A list of lists, with the elements representing the values of each constant element in the tensor. E.g., `[[5, 22, 0], [14, 5, 44]]`." ) ``` A list of lists, with the elements representing the initial values of each constant element in the tensor. E.g., `[[5, 22, 0], [14, 5, 44]]`. ##### __getitem__ ``` __getitem__(indices: int | tuple[int]) -> Constant ``` Implements random access for TensorConstant. Note Indexing is assumed to start at 1. Parameters: | Name | Type | Description | Default | | --------- | ----- | ------------ | -------------------------------------- | | `indices` | \`int | Tuple[int]\` | a single integer or tuple of integers. | Returns: | Name | Type | Description | | ---------- | ---------- | --------------------------------------------------------------------------------------------------------------------- | | `Constant` | `Constant` | A new instance of Constant that has been setup with information found at the specified indices in the TensorConstant. | Source code in `desdeo/problem/schema.py` ``` def __getitem__(self, indices: int | tuple[int]) -> Constant: """Implements random access for TensorConstant. Note: Indexing is assumed to start at 1. Args: indices (int | Tuple[int]): a single integer or tuple of integers. Returns: Constant: A new instance of Constant that has been setup with information found at the specified indices in the TensorConstant. """ if isinstance(indices, tuple): # multi-dimensional indexing name = f"{self.name} at position {[*indices]}" symbol = f"{self.symbol}_{'_'.join(map(str, indices))}" value = self.get_values() for idx in indices: value = value[idx - 1] else: # single indexing name = f"{self.name} at position [{indices}]" symbol = f"{self.symbol}_{indices}" value = self.get_values()[indices - 1] return Constant(name=name, symbol=symbol, value=value) ``` ##### get_values ``` get_values() -> ( Iterable[VariableType | Iterable[VariableType]] | Iterable[None, Iterable[None]] ) ``` Return the constant values as a Python iterable (e.g., list of list). Source code in `desdeo/problem/schema.py` ``` def get_values(self) -> Iterable[VariableType | Iterable[VariableType]] | Iterable[None, Iterable[None]]: """Return the constant values as a Python iterable (e.g., list of list).""" values = get_tensor_values(self.values) if isinstance(values, VariableType | None): return np.full(self.shape, values).tolist() return values ``` ##### to_constants ``` to_constants() -> list[Constant] ``` Flatten the tensor into a list of Constants. Returns: | Type | Description | | ---------------- | -------------------------------------- | | `list[Constant]` | list\[Constant\]: a list of Constants. | Source code in `desdeo/problem/schema.py` ``` def to_constants(self) -> list[Constant]: """Flatten the tensor into a list of Constants. Returns: list[Constant]: a list of Constants. """ constants = [] for indices in list(product(*[range(1, dim + 1) for dim in self.shape])): constants.append(self[*indices]) return constants ``` #### TensorVariable Bases: `BaseModel` Model for a tensor, e.g., vector variable. Source code in `desdeo/problem/schema.py` ``` class TensorVariable(BaseModel): """Model for a tensor, e.g., vector variable.""" model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True, from_attributes=True, extra="forbid") name: str = Field( description="Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'." ) """Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'.""" symbol: str = Field( description=( "Symbol to represent the variable. This will be used in the rest of the problem definition." " Notice that the elements of the tensor will be represented with the symbol followed by" " indices. E.g., the first element of the third element of a 2-dimensional tensor," " is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable." " Note that indexing starts from 1." ) ) """ Symbol to represent the variable. This will be used in the rest of the problem definition. Notice that the elements of the tensor will be represented with the symbol followed by indices. E.g., the first element of the third element of a 2-dimensional tensor, is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable. Note that indexing starts from 1. """ variable_type: VariableTypeEnum = Field( description=( "Type of the variable. Can be real, integer, or binary. " "Note that each element of a TensorVariable is assumed to be of the same type." ) ) """Type of the variable. Can be real, integer, or binary. Note that each element of a TensorVariable is assumed to be of the same type.""" shape: list[int] = Field( description=( "A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns." ) ) """A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns. """ lowerbounds: Tensor | None = Field( description=( "A list of lists, with the elements representing the lower bounds of each element. " "E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the lower " "bound of each element. Defaults to None." ), default=None, ) """A list of lists, with the elements representing the lower bounds of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the lower bound of each element. Defaults to None.""" upperbounds: Tensor | VariableType | None = Field( description=( "A list of lists, with the elements representing the upper bounds of each " "element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, " "that value is assumed to be the upper bound of each element. Defaults to " "None." ), default=None, ) """A list of lists, with the elements representing the upper bounds of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the upper bound of each element. Defaults to None.""" initial_values: Tensor | VariableType | None = Field( description=( "A list of lists, with the elements representing the initial values of " "each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is " "supplied, that value is assumed to be the initial value of each element. " "Defaults to None." ), default=None, ) """A list of lists, with the elements representing the initial values of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the initial value of each element. Defaults to None.""" _parse_list_to_mathjson = field_validator("lowerbounds", "upperbounds", "initial_values", mode="before")( parse_list_to_mathjson ) def get_lowerbound_values( self, ) -> Iterable[VariableType | Iterable[VariableType]] | Iterable[None | Iterable[None]]: """Return the lowerbounds values, if any, as a Python iterable (list of list).""" lowerbounds = get_tensor_values(self.lowerbounds) if isinstance(lowerbounds, VariableType | None): # single value, construct list with the correct dimensions return np.full(self.shape, lowerbounds).tolist() return lowerbounds def get_upperbound_values( self, ) -> Iterable[VariableType | Iterable[VariableType]] | Iterable[None | Iterable[None]]: """Return the upperbounds values, if any, as a Python iterable (list of list).""" upperbounds = get_tensor_values(self.upperbounds) if isinstance(upperbounds, VariableType | None): # single value, construct list with the correct dimensions return np.full(self.shape, upperbounds).tolist() return upperbounds def get_initial_values(self) -> Iterable[VariableType | Iterable[VariableType]] | Iterable[None | Iterable[None]]: """Return the initial values, if any, as a Python iterable (list of list).""" values = get_tensor_values(self.initial_values) if isinstance(values, VariableType | None): # single value, construct list with the correct dimensions return np.full(self.shape, values).tolist() return values def to_variables(self) -> list[Variable]: """Flatten the tensor into a list of Variables. Returns: list[Variable]: a list of Variables. """ variables = [] for indices in list(product(*[range(1, dim + 1) for dim in self.shape])): variables.append(self[*indices]) return variables def __getitem__(self, indices: int | tuple[int]) -> Variable: """Implements random access for TensorVariable. Note: Indexing is assumed to start at 1. Args: indices (int | Tuple[int]): a single integer or tuple of integers. Returns: Variable: A new instance of Variable that has been setup with information found at the specified indices in the TensorVariable. """ if isinstance(indices, tuple): # multi-dimensional indexing name = f"{self.name} at position {[*indices]}" symbol = f"{self.symbol}_{'_'.join(map(str, indices))}" lowerbound = self.get_lowerbound_values() upperbound = self.get_upperbound_values() initial_value = self.get_initial_values() for idx in indices: lowerbound = lowerbound[idx - 1] upperbound = upperbound[idx - 1] initial_value = initial_value[idx - 1] else: # single indexing name = f"{self.name} at position [{indices}]" symbol = f"{self.symbol}_{indices}" lowerbound = self.get_lowerbound_values()[indices - 1] upperbound = self.get_upperbound_values()[indices - 1] initial_value = self.get_initial_values()[indices - 1] return Variable( name=name, symbol=symbol, variable_type=self.variable_type, lowerbound=lowerbound, upperbound=upperbound, initial_value=initial_value, ) ``` ##### initial_values ``` initial_values: Tensor | VariableType | None = Field( description="A list of lists, with the elements representing the initial values of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the initial value of each element. Defaults to None.", default=None, ) ``` A list of lists, with the elements representing the initial values of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the initial value of each element. Defaults to None. ##### lowerbounds ``` lowerbounds: Tensor | None = Field( description="A list of lists, with the elements representing the lower bounds of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the lower bound of each element. Defaults to None.", default=None, ) ``` A list of lists, with the elements representing the lower bounds of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the lower bound of each element. Defaults to None. ##### name ``` name: str = Field( description="Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'." ) ``` Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'. ##### shape ``` shape: list[int] = Field( description="A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns." ) ``` A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns. ##### symbol ``` symbol: str = Field( description="Symbol to represent the variable. This will be used in the rest of the problem definition. Notice that the elements of the tensor will be represented with the symbol followed by indices. E.g., the first element of the third element of a 2-dimensional tensor, is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable. Note that indexing starts from 1." ) ``` Symbol to represent the variable. This will be used in the rest of the problem definition. Notice that the elements of the tensor will be represented with the symbol followed by indices. E.g., the first element of the third element of a 2-dimensional tensor, is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable. Note that indexing starts from 1. ##### upperbounds ``` upperbounds: Tensor | VariableType | None = Field( description="A list of lists, with the elements representing the upper bounds of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the upper bound of each element. Defaults to None.", default=None, ) ``` A list of lists, with the elements representing the upper bounds of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the upper bound of each element. Defaults to None. ##### variable_type ``` variable_type: VariableTypeEnum = Field( description="Type of the variable. Can be real, integer, or binary. Note that each element of a TensorVariable is assumed to be of the same type." ) ``` Type of the variable. Can be real, integer, or binary. Note that each element of a TensorVariable is assumed to be of the same type. ##### __getitem__ ``` __getitem__(indices: int | tuple[int]) -> Variable ``` Implements random access for TensorVariable. Note Indexing is assumed to start at 1. Parameters: | Name | Type | Description | Default | | --------- | ----- | ------------ | -------------------------------------- | | `indices` | \`int | Tuple[int]\` | a single integer or tuple of integers. | Returns: | Name | Type | Description | | ---------- | ---------- | --------------------------------------------------------------------------------------------------------------------- | | `Variable` | `Variable` | A new instance of Variable that has been setup with information found at the specified indices in the TensorVariable. | Source code in `desdeo/problem/schema.py` ``` def __getitem__(self, indices: int | tuple[int]) -> Variable: """Implements random access for TensorVariable. Note: Indexing is assumed to start at 1. Args: indices (int | Tuple[int]): a single integer or tuple of integers. Returns: Variable: A new instance of Variable that has been setup with information found at the specified indices in the TensorVariable. """ if isinstance(indices, tuple): # multi-dimensional indexing name = f"{self.name} at position {[*indices]}" symbol = f"{self.symbol}_{'_'.join(map(str, indices))}" lowerbound = self.get_lowerbound_values() upperbound = self.get_upperbound_values() initial_value = self.get_initial_values() for idx in indices: lowerbound = lowerbound[idx - 1] upperbound = upperbound[idx - 1] initial_value = initial_value[idx - 1] else: # single indexing name = f"{self.name} at position [{indices}]" symbol = f"{self.symbol}_{indices}" lowerbound = self.get_lowerbound_values()[indices - 1] upperbound = self.get_upperbound_values()[indices - 1] initial_value = self.get_initial_values()[indices - 1] return Variable( name=name, symbol=symbol, variable_type=self.variable_type, lowerbound=lowerbound, upperbound=upperbound, initial_value=initial_value, ) ``` ##### get_initial_values ``` get_initial_values() -> ( Iterable[VariableType | Iterable[VariableType]] | Iterable[None | Iterable[None]] ) ``` Return the initial values, if any, as a Python iterable (list of list). Source code in `desdeo/problem/schema.py` ``` def get_initial_values(self) -> Iterable[VariableType | Iterable[VariableType]] | Iterable[None | Iterable[None]]: """Return the initial values, if any, as a Python iterable (list of list).""" values = get_tensor_values(self.initial_values) if isinstance(values, VariableType | None): # single value, construct list with the correct dimensions return np.full(self.shape, values).tolist() return values ``` ##### get_lowerbound_values ``` get_lowerbound_values() -> ( Iterable[VariableType | Iterable[VariableType]] | Iterable[None | Iterable[None]] ) ``` Return the lowerbounds values, if any, as a Python iterable (list of list). Source code in `desdeo/problem/schema.py` ``` def get_lowerbound_values( self, ) -> Iterable[VariableType | Iterable[VariableType]] | Iterable[None | Iterable[None]]: """Return the lowerbounds values, if any, as a Python iterable (list of list).""" lowerbounds = get_tensor_values(self.lowerbounds) if isinstance(lowerbounds, VariableType | None): # single value, construct list with the correct dimensions return np.full(self.shape, lowerbounds).tolist() return lowerbounds ``` ##### get_upperbound_values ``` get_upperbound_values() -> ( Iterable[VariableType | Iterable[VariableType]] | Iterable[None | Iterable[None]] ) ``` Return the upperbounds values, if any, as a Python iterable (list of list). Source code in `desdeo/problem/schema.py` ``` def get_upperbound_values( self, ) -> Iterable[VariableType | Iterable[VariableType]] | Iterable[None | Iterable[None]]: """Return the upperbounds values, if any, as a Python iterable (list of list).""" upperbounds = get_tensor_values(self.upperbounds) if isinstance(upperbounds, VariableType | None): # single value, construct list with the correct dimensions return np.full(self.shape, upperbounds).tolist() return upperbounds ``` ##### to_variables ``` to_variables() -> list[Variable] ``` Flatten the tensor into a list of Variables. Returns: | Type | Description | | ---------------- | -------------------------------------- | | `list[Variable]` | list\[Variable\]: a list of Variables. | Source code in `desdeo/problem/schema.py` ``` def to_variables(self) -> list[Variable]: """Flatten the tensor into a list of Variables. Returns: list[Variable]: a list of Variables. """ variables = [] for indices in list(product(*[range(1, dim + 1) for dim in self.shape])): variables.append(self[*indices]) return variables ``` #### Url Bases: `BaseModel` Model for a URL. Source code in `desdeo/problem/schema.py` ``` class Url(BaseModel): """Model for a URL.""" model_config = ConfigDict(frozen=True, from_attributes=True, extra="forbid") url: str = Field( description=( "A URL to the simulator. A GET request to this URL should be used to evaluate solutions in batches." ) ) """A URL to the simulator. A GET request to this URL should be used to evaluate solutions in batches.""" auth: tuple[str, str] | None = Field( description=( "Optional. A tuple of username and password to be used for authentication when making requests to the URL." ), default=None, ) """Optional. A tuple of username and password to be used for authentication when making requests to the URL.""" ``` ##### auth ``` auth: tuple[str, str] | None = Field( description="Optional. A tuple of username and password to be used for authentication when making requests to the URL.", default=None, ) ``` Optional. A tuple of username and password to be used for authentication when making requests to the URL. ##### url ``` url: str = Field( description="A URL to the simulator. A GET request to this URL should be used to evaluate solutions in batches." ) ``` A URL to the simulator. A GET request to this URL should be used to evaluate solutions in batches. #### Variable Bases: `BaseModel` Model for a variable. Source code in `desdeo/problem/schema.py` ``` class Variable(BaseModel): """Model for a variable.""" model_config = ConfigDict(frozen=True, from_attributes=True, extra="forbid") name: str = Field( description="Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'." ) """Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'.""" symbol: str = Field( description=( "Symbol to represent the variable. This will be used in the rest of the problem definition." " It may also be used in UIs and visualizations. Example: 'v_1'." ), ) """ Symbol to represent the variable. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'v_1'.""" variable_type: VariableTypeEnum = Field(description="Type of the variable. Can be real, integer or binary.") """Type of the variable. Can be real, integer or binary.""" lowerbound: VariableType | None = Field(description="Lower bound of the variable.", default=None) """Lower bound of the variable. Defaults to `None`.""" upperbound: VariableType | None = Field(description="Upper bound of the variable.", default=None) """Upper bound of the variable. Defaults to `None`.""" initial_value: VariableType | None = Field( description="Initial value of the variable. This is optional.", default=None ) """Initial value of the variable. This is optional. Defaults to `None`.""" ``` ##### initial_value ``` initial_value: VariableType | None = Field( description="Initial value of the variable. This is optional.", default=None, ) ``` Initial value of the variable. This is optional. Defaults to `None`. ##### lowerbound ``` lowerbound: VariableType | None = Field( description="Lower bound of the variable.", default=None ) ``` Lower bound of the variable. Defaults to `None`. ##### name ``` name: str = Field( description="Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'." ) ``` Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'. ##### symbol ``` symbol: str = Field( description="Symbol to represent the variable. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'v_1'." ) ``` Symbol to represent the variable. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'v_1'. ##### upperbound ``` upperbound: VariableType | None = Field( description="Upper bound of the variable.", default=None ) ``` Upper bound of the variable. Defaults to `None`. ##### variable_type ``` variable_type: VariableTypeEnum = Field( description="Type of the variable. Can be real, integer or binary." ) ``` Type of the variable. Can be real, integer or binary. #### VariableDomainTypeEnum Bases: `StrEnum` An enumerator for the possible variable type domains of a problem. Source code in `desdeo/problem/schema.py` ``` class VariableDomainTypeEnum(StrEnum): """An enumerator for the possible variable type domains of a problem.""" continuous = "continuous" """All variables are real valued.""" binary = "binary" """All variables are binary valued.""" integer = "integer" """All variables are integer or binary valued.""" mixed = "mixed" """Some variables are continuos, some are integer or binary.""" ``` ##### binary ``` binary = 'binary' ``` All variables are binary valued. ##### continuous ``` continuous = 'continuous' ``` All variables are real valued. ##### integer ``` integer = 'integer' ``` All variables are integer or binary valued. ##### mixed ``` mixed = 'mixed' ``` Some variables are continuos, some are integer or binary. #### VariableTypeEnum Bases: `StrEnum` An enumerator for possible variable types. Source code in `desdeo/problem/schema.py` ``` class VariableTypeEnum(StrEnum): """An enumerator for possible variable types.""" real = "real" """A continuous variable.""" integer = "integer" """An integer variable.""" binary = "binary" """A binary variable.""" ``` ##### binary ``` binary = 'binary' ``` A binary variable. ##### integer ``` integer = 'integer' ``` An integer variable. ##### real ``` real = 'real' ``` A continuous variable. #### get_tensor_values ``` get_tensor_values( values: Iterable[VariableType | Iterable[VariableType]] | VariableType | None, ) -> ( Iterable[VariableType | Iterable[VariableType]] | VariableType | None ) ``` Return the values for a given attribute as a nested Python list or single value. Removes the 'List' entries from the JSON format to give a Python compatible list. If the values are a single value or None, then a single value or None is returned instead, respectively. Parameters: | Name | Type | Description | Default | | -------- | ------------------------ | ------------------------ | ------------ | | `values` | \`Iterable\[VariableType | Iterable[VariableType]\] | VariableType | Returns: | Type | Description | | ------------------------ | ------------------------ | | \`Iterable\[VariableType | Iterable[VariableType]\] | Source code in `desdeo/problem/schema.py` ``` def get_tensor_values( values: Iterable[VariableType | Iterable[VariableType]] | VariableType | None, ) -> Iterable[VariableType | Iterable[VariableType]] | VariableType | None: """Return the values for a given attribute as a nested Python list or single value. Removes the 'List' entries from the JSON format to give a Python compatible list. If the values are a single value or None, then a single value or None is returned instead, respectively. Arguments: values (Iterable[VariableType | Iterable[VariableType]] | VariableType | None): the values that should be extracted as a Python list. Returns: list[VariableType] | Iterable[list[VariableType]] | VariableType| None: a list with shape `self.shape` with the values defined for the variable. If a single values consisted of a single value or None instead, then a single valuer or None are returned, respectively. """ if values is None or isinstance(values, VariableType): return values if isinstance(values, list) and len(values) > 1: if values[0] == "List" and isinstance(values[1], list): # recursive case, encountered list return [get_tensor_values(v_element) for v_element in values[1:]] if values[0] == "List": # terminal case, encountered a VariableType return [*values[1:]] # if anything else is encountered, raise an error msg = "Encountered value that is not a valid VariableType nor a list." raise ValueError(msg) msg = f"Values must be a valid MathJSON vector. Got {type(values)}." raise ValueError(msg) ``` #### parse_infix_to_func ``` parse_infix_to_func(cls: Problem, v: str | list) -> list ``` Validator that checks if the 'func' field is of type str or list. If str, then it is assumed the string represents the func in infix notation. The string is parsed in the validator. If list, then the func is assumed to be represented in Math JSON format. Parameters: | Name | Type | Description | Default | | ----- | --------- | ------------------------------------------------------------ | ------------------------- | | `cls` | `Problem` | the class of the pydantic model the validator is applied to. | *required* | | `v` | \`str | list\` | The func to be validated. | Raises: | Type | Description | | ------------ | ------------------------------------------ | | `ValueError` | v is neither an instance of str or a list. | Returns: | Name | Type | Description | | ------ | ------ | ----------------------------------------- | | `list` | `list` | The func represented in Math JSON format. | Source code in `desdeo/problem/schema.py` ``` def parse_infix_to_func(cls: "Problem", v: str | list) -> list: """Validator that checks if the 'func' field is of type str or list. If str, then it is assumed the string represents the func in infix notation. The string is parsed in the validator. If list, then the func is assumed to be represented in Math JSON format. Args: cls: the class of the pydantic model the validator is applied to. v (str | list): The func to be validated. Raises: ValueError: v is neither an instance of str or a list. Returns: list: The func represented in Math JSON format. """ if v is None: return v # Check if v is a string (infix expression), then parse it if isinstance(v, str): parser = InfixExpressionParser() return parser.parse(v) # If v is already in the correct format (a list), just return it if isinstance(v, list): return v # Raise an error if v is neither a string nor a list msg = f"The function expressions must be a string (infix expression) or a list. Got {type(v)}." raise ValueError(msg) ``` #### parse_list_to_mathjson ``` parse_list_to_mathjson( cls: TensorVariable, v: Tensor | VariableType | None ) -> list ``` Validator that makes sure a nested Python list is represented as tensor following the MathJSON convention. Parameters: | Name | Type | Description | Default | | ----- | ---------------- | ------------------------------------------------------------ | ---------- | | `cls` | `TensorVariable` | the class of the pydantic model the validator is applied to. | *required* | | `v` | \`Tensor | VariableType | None\` | Returns: | Name | Type | Description | | ------ | ------ | ---------------------------------------------------------------------------------------------------------------- | | `list` | `list` | a tensor following the MathJSON conventions; or a single value or None, if v was assigned to one of these types. | Source code in `desdeo/problem/schema.py` ``` def parse_list_to_mathjson(cls: "TensorVariable", v: Tensor | VariableType | None) -> list: """Validator that makes sure a nested Python list is represented as tensor following the MathJSON convention. Args: cls (TensorVariable): the class of the pydantic model the validator is applied to. v (Tensor | VariableType | None): the nested lists to be validated. Returns: list: a tensor following the MathJSON conventions; or a single value or None, if v was assigned to one of these types. """ if v is None or isinstance(v, VariableType): return v # Check if the input is already in MathJSON format if isinstance(v, list) and len(v) > 0 and v[0] == "List": return v # recursively parse into a MathJSON representation if isinstance(v, list) and len(v) > 0: if v[0] == "List": # assumed to be already in MathJson format, just return the list return v if isinstance(v[0], list): # recursive case, encountered list return ["List", *[parse_list_to_mathjson(TensorVariable, v_element) for v_element in v]] if isinstance(v[0], VariableType | None): # terminal case, encountered a VariableType return ["List", *v] # if anything else is encountered, raise an error msg = "Encountered value that is not a valid VariableType nor a list." raise ValueError(msg) msg = f"The tensor must a Python list (of lists) or a single value of type VariableType. Got {type(v)}." raise ValueError(msg) ``` #### tensor_custom_error_validator ``` tensor_custom_error_validator( value: Any, handler: ValidatorFunctionWrapHandler, _info: ValidationInfo, ) -> Any ``` Custom error handler to simplify error messages related to recursive tensor types. Parameters: | Name | Type | Description | Default | | --------- | ------------------------------ | -------------------------------------------- | ---------- | | `value` | `Any` | input value to be validated. | *required* | | `handler` | `ValidatorFunctionWrapHandler` | handler to check the values. | *required* | | `_info` | `ValidationInfo` | info related to the validation of the value. | *required* | Raises: | Type | Description | | --------------------- | ----------------------------------------- | | `PydanticCustomError` | when the value is an invalid tensor type. | Returns: | Name | Type | Description | | ----- | ----- | --------------- | | `Any` | `Any` | a valid tensor. | Source code in `desdeo/problem/schema.py` ``` def tensor_custom_error_validator(value: Any, handler: ValidatorFunctionWrapHandler, _info: ValidationInfo) -> Any: """Custom error handler to simplify error messages related to recursive tensor types. Args: value (Any): input value to be validated. handler (ValidatorFunctionWrapHandler): handler to check the values. _info (ValidationInfo): info related to the validation of the value. Raises: PydanticCustomError: when the value is an invalid tensor type. Returns: Any: a valid tensor. """ try: return handler(value) except ValidationError as exc: raise PydanticCustomError("invalid tensor", "Input is not a valid tensor") from exc ``` ## Scenario Scenario model for representing and constructing scenario-based optimization problems. ### Scenario Bases: `BaseModel` References elements from the ScenarioModel pools that apply to a specific scenario. Each field maps a target symbol to a pool index. The symbol identifies which element in the base problem to replace (for existing symbols) or the label of a new element to add (for symbols not present in the base problem). The index is the position of the replacement or addition in the corresponding ScenarioModel pool list. Using an index rather than a symbol allows multiple pool entries to share the same symbol (e.g. the same constant at different values across scenarios) without ambiguity. Source code in `desdeo/problem/scenario.py` ``` class Scenario(BaseModel): """References elements from the ScenarioModel pools that apply to a specific scenario. Each field maps a target symbol to a pool index. The symbol identifies which element in the base problem to replace (for existing symbols) or the label of a new element to add (for symbols not present in the base problem). The index is the position of the replacement or addition in the corresponding ScenarioModel pool list. Using an index rather than a symbol allows multiple pool entries to share the same symbol (e.g. the same constant at different values across scenarios) without ambiguity. """ model_config = ConfigDict(frozen=True) constants: dict[str, int] = Field( default={}, description="Maps target symbol to pool index for constants (scalar or tensor).", ) variables: dict[str, int] = Field( default={}, description="Maps target symbol to pool index for variables (scalar or tensor).", ) objectives: dict[str, int] = Field( default={}, description="Maps target symbol to pool index for objectives.", ) constraints: dict[str, int] = Field( default={}, description="Maps target symbol to pool index for constraints.", ) extra_funcs: dict[str, int] = Field( default={}, description="Maps target symbol to pool index for extra functions.", ) scalarization_funcs: dict[str, int] = Field( default={}, description="Maps target symbol to pool index for scalarization functions.", ) ``` ### ScenarioModel Bases: `BaseModel` Base class for scenario models using Pydantic. Source code in `desdeo/problem/scenario.py` ``` class ScenarioModel(BaseModel): """Base class for scenario models using Pydantic.""" model_config = ConfigDict(frozen=True) scenario_tree: dict[str, list[str]] = Field( description="A dictionary describing the scenario structure for the problem. " "Keys are scenario names, values are lists of child scenario names. " "Must contain root of the tree with key 'ROOT' and value being a list of top-level scenario names. " "A plain list of scenario names is also accepted and is automatically converted to {'ROOT': [...]}.", default={"ROOT": ["scenario_0"]}, ) @field_validator("scenario_tree", mode="before") @classmethod def coerce_list_to_tree(cls, v): """Normalise the scenario tree input. - A flat list of names is converted to ``{'ROOT': [...], name: [], ...}``. - A dict may omit leaf nodes (nodes that appear as children but have no own entry). Missing entries are auto-inserted with an empty child list. """ if isinstance(v, list): return {"ROOT": v, **{name: [] for name in v}} if isinstance(v, dict): # Keep the order the children are declared in: the tree's key order decides # the order of the leaf scenarios, and that in turn orders the elements of a # combined scenario problem. all_children = dict.fromkeys(child for children in v.values() for child in children) missing_leaves = [name for name in all_children if name not in v] if missing_leaves: return {**v, **{name: [] for name in missing_leaves}} return v @field_validator("scenario_tree", mode="after") @classmethod def validate_tree_structure(cls, v): """Verify that scenario_tree is a valid rooted tree with ROOT as the universal ancestor.""" if "ROOT" not in v: raise ValueError("scenario_tree must contain a 'ROOT' key.") child_counts: dict[str, int] = {} for children in v.values(): for child in children: child_counts[child] = child_counts.get(child, 0) + 1 if "ROOT" in child_counts: raise ValueError("'ROOT' must not appear as a child of any node.") multi_parent = [n for n, c in child_counts.items() if c > 1] if multi_parent: raise ValueError(f"Nodes have more than one parent (not a tree): {sorted(multi_parent)}.") visited: set[str] = set() stack = ["ROOT"] while stack: node = stack.pop() visited.add(node) stack.extend(v.get(node, [])) unreachable = set(v) - visited if unreachable: raise ValueError(f"Nodes not reachable from ROOT: {sorted(unreachable)}.") return v scenario_probabilities: dict[str, float] = Field( default={}, description="Maps each scenario tree node to its probability. ROOT is always included with probability 1.0. " "For every node, the probabilities of its children must sum to the node's own probability.", ) @field_validator("scenario_probabilities", mode="before") @classmethod def coerce_none_probabilities(cls, v): """Coerce None to an empty dict so probability validation can be skipped.""" return v if v is not None else {} @field_validator("scenario_probabilities", mode="after") @classmethod def validate_scenario_probabilities(cls, v, info): """Auto-inject ROOT=1.0 and verify child probabilities sum to their parent's probability.""" if not v: return v tree: dict[str, list[str]] = info.data.get("scenario_tree", {}) v.setdefault("ROOT", 1.0) for key in v: if key not in tree: raise ValueError(f"scenario_probabilities key '{key}' not found in scenario_tree.") for parent, children in tree.items(): if not children: continue if not any(c in v for c in children): continue parent_prob = v.get(parent) if parent_prob is None: raise ValueError(f"Probability for node '{parent}' is missing.") missing = [c for c in children if c not in v] if missing: raise ValueError(f"Probabilities missing for children of '{parent}': {missing}.") child_sum = sum(v[c] for c in children) if not math.isclose(child_sum, parent_prob, rel_tol=1e-9): raise ValueError(f"Probabilities of children of '{parent}' sum to {child_sum}, expected {parent_prob}.") return v base_problem: "Problem" = Field(description="The base Problem instance that is modified for different scenarios.") constants: tuple["Constant | TensorConstant", ...] = Field( default=(), description="Pool of Constant and TensorConstant replacements available to scenarios.", ) variables: tuple["Variable | TensorVariable", ...] = Field( default=(), description="Pool of Variable and TensorVariable replacements available to scenarios.", ) objectives: tuple["Objective", ...] = Field( default=(), description="Pool of Objective replacements available to scenarios.", ) constraints: tuple["Constraint", ...] = Field( default=(), description="Pool of Constraint replacements available to scenarios.", ) extra_funcs: tuple["ExtraFunction", ...] = Field( default=(), description="Pool of ExtraFunction replacements available to scenarios.", ) scalarization_funcs: tuple["ScalarizationFunction", ...] = Field( default=(), description="Pool of ScalarizationFunction replacements available to scenarios.", ) scenarios: dict[str, "Scenario"] = Field( default={}, description="A dictionary mapping scenario names to Scenario instances, " "which define which elements from the pools apply to each scenario.", ) anticipation_stop: dict[str, list[str]] = Field( default={}, description="Maps a scenario tree node name to a list of variable symbols that enforce " "non-anticipativity at that node: the listed variables must take the same value across " "all descendant scenarios of that node.", ) @field_validator("anticipation_stop", mode="after") @classmethod def validate_anticipation_stop(cls, v, info): """Validate that anticipation_stop keys exist in scenario_tree and values are valid variable symbols.""" data = info.data valid_nodes = set(data.get("scenario_tree", {}).keys()) base_problem = data.get("base_problem") valid_variables = ( {var.symbol for var in base_problem.variables} if base_problem and base_problem.variables else set() ) # Pool variables (added to scenarios) are also valid anticipation targets. valid_variables |= {var.symbol for var in data.get("variables", ())} for node, symbols in v.items(): if node not in valid_nodes: raise ValueError(f"anticipation_stop key '{node}' not found in scenario_tree.") for symbol in symbols: if symbol not in valid_variables: raise ValueError( f"Variable symbol '{symbol}' in anticipation_stop['{node}'] " "not found in base_problem variables or the variable pool." ) return v def with_base_problem( self, problem: "Problem | None" = None, validate: bool = False, **updates: dict[str, any] ) -> "ScenarioModel": """Return a new ScenarioModel with the base_problem updated. By default uses model_copy, so validators are NOT re-run. Pass ``validate=True`` to reconstruct via model_validate, which re-runs all field validators (including anticipation_stop checks). Only safe when the update cannot remove variables or scenario-tree nodes that validators reference. Args: problem: if provided, replaces the base_problem entirely. validate: if True, reconstruct with model_validate so all validators run, which is somewhat slower. Defaults to False. **updates: keyword arguments forwarded to Problem.model_copy(update=...) to partially update the existing base_problem. Ignored when ``problem`` is given. Returns: A new ScenarioModel with the modified base_problem. """ new_base = problem if problem is not None else self.base_problem.model_copy(update=updates) if validate: return type(self).model_validate(self.model_dump() | {"base_problem": new_base}) return self.model_copy(update={"base_problem": new_base}) @cached_property def leaf_scenarios(self) -> MappingProxyType[str, float]: """Return a read-only mapping from each leaf scenario name to its probability. Leaf scenarios are nodes in the scenario tree with no children that also appear in the scenarios dict. If scenario_probabilities is empty, equal weights (1/n) are assigned to each leaf. """ leaves = [ n for n, children in self.scenario_tree.items() if n != "ROOT" and not children and n in self.scenarios ] if self.scenario_probabilities: return MappingProxyType({leaf: self.scenario_probabilities[leaf] for leaf in leaves}) equal = 1.0 / len(leaves) if leaves else 0.0 return MappingProxyType(dict.fromkeys(leaves, equal)) def get_scenario_problem(self, scenario_name: str) -> "Problem": """Return a modified copy of base_problem with the elements defined in the named scenario applied.""" if scenario_name not in self.scenarios: raise ValueError(f"Scenario '{scenario_name}' not found.") scenario = self.scenarios[scenario_name] def apply(base_list, pool_list, symbol_to_idx): if not symbol_to_idx: return base_list base_list = base_list or [] base_symbols = {e.symbol for e in base_list} result = [pool_list[symbol_to_idx[e.symbol]] if e.symbol in symbol_to_idx else e for e in base_list] result += [pool_list[idx] for sym, idx in symbol_to_idx.items() if sym not in base_symbols] return result updates = {} if scenario.constants: updates["constants"] = apply(self.base_problem.constants, self.constants, scenario.constants) if scenario.variables: updates["variables"] = apply(self.base_problem.variables, self.variables, scenario.variables) if scenario.objectives: updates["objectives"] = apply(self.base_problem.objectives, self.objectives, scenario.objectives) if scenario.constraints: updates["constraints"] = apply(self.base_problem.constraints, self.constraints, scenario.constraints) if scenario.extra_funcs: updates["extra_funcs"] = apply(self.base_problem.extra_funcs, self.extra_funcs, scenario.extra_funcs) if scenario.scalarization_funcs: updates["scalarization_funcs"] = apply( self.base_problem.scalarization_funcs, self.scalarization_funcs, scenario.scalarization_funcs ) return self.base_problem.model_copy(update=updates) @field_validator("scenarios", mode="after") @classmethod def validate_scenarios(cls, v, info): """Validate that scenario names exist in scenario_tree and that all indices are in bounds.""" data = info.data valid_scenarios = set(data.get("scenario_tree", {}).keys()) pool_lengths = { "constants": len(data.get("constants", [])), "variables": len(data.get("variables", [])), "objectives": len(data.get("objectives", [])), "constraints": len(data.get("constraints", [])), "extra_funcs": len(data.get("extra_funcs", [])), "scalarization_funcs": len(data.get("scalarization_funcs", [])), } for scenario_name, scenario in v.items(): if scenario_name not in valid_scenarios: raise ValueError(f"Scenario '{scenario_name}' not found in scenario_tree.") for field, length in pool_lengths.items(): for symbol, idx in getattr(scenario, field).items(): if idx < 0 or idx >= length: raise ValueError( f"Index {idx} for symbol '{symbol}' in scenario '{scenario_name}.{field}' " f"is out of bounds (pool length {length})." ) return v ``` #### leaf_scenarios ``` leaf_scenarios: MappingProxyType[str, float] ``` Return a read-only mapping from each leaf scenario name to its probability. Leaf scenarios are nodes in the scenario tree with no children that also appear in the scenarios dict. If scenario_probabilities is empty, equal weights (1/n) are assigned to each leaf. #### coerce_list_to_tree ``` coerce_list_to_tree(v) ``` Normalise the scenario tree input. - A flat list of names is converted to `{'ROOT': [...], name: [], ...}`. - A dict may omit leaf nodes (nodes that appear as children but have no own entry). Missing entries are auto-inserted with an empty child list. Source code in `desdeo/problem/scenario.py` ``` @field_validator("scenario_tree", mode="before") @classmethod def coerce_list_to_tree(cls, v): """Normalise the scenario tree input. - A flat list of names is converted to ``{'ROOT': [...], name: [], ...}``. - A dict may omit leaf nodes (nodes that appear as children but have no own entry). Missing entries are auto-inserted with an empty child list. """ if isinstance(v, list): return {"ROOT": v, **{name: [] for name in v}} if isinstance(v, dict): # Keep the order the children are declared in: the tree's key order decides # the order of the leaf scenarios, and that in turn orders the elements of a # combined scenario problem. all_children = dict.fromkeys(child for children in v.values() for child in children) missing_leaves = [name for name in all_children if name not in v] if missing_leaves: return {**v, **{name: [] for name in missing_leaves}} return v ``` #### coerce_none_probabilities ``` coerce_none_probabilities(v) ``` Coerce None to an empty dict so probability validation can be skipped. Source code in `desdeo/problem/scenario.py` ``` @field_validator("scenario_probabilities", mode="before") @classmethod def coerce_none_probabilities(cls, v): """Coerce None to an empty dict so probability validation can be skipped.""" return v if v is not None else {} ``` #### get_scenario_problem ``` get_scenario_problem(scenario_name: str) -> Problem ``` Return a modified copy of base_problem with the elements defined in the named scenario applied. Source code in `desdeo/problem/scenario.py` ``` def get_scenario_problem(self, scenario_name: str) -> "Problem": """Return a modified copy of base_problem with the elements defined in the named scenario applied.""" if scenario_name not in self.scenarios: raise ValueError(f"Scenario '{scenario_name}' not found.") scenario = self.scenarios[scenario_name] def apply(base_list, pool_list, symbol_to_idx): if not symbol_to_idx: return base_list base_list = base_list or [] base_symbols = {e.symbol for e in base_list} result = [pool_list[symbol_to_idx[e.symbol]] if e.symbol in symbol_to_idx else e for e in base_list] result += [pool_list[idx] for sym, idx in symbol_to_idx.items() if sym not in base_symbols] return result updates = {} if scenario.constants: updates["constants"] = apply(self.base_problem.constants, self.constants, scenario.constants) if scenario.variables: updates["variables"] = apply(self.base_problem.variables, self.variables, scenario.variables) if scenario.objectives: updates["objectives"] = apply(self.base_problem.objectives, self.objectives, scenario.objectives) if scenario.constraints: updates["constraints"] = apply(self.base_problem.constraints, self.constraints, scenario.constraints) if scenario.extra_funcs: updates["extra_funcs"] = apply(self.base_problem.extra_funcs, self.extra_funcs, scenario.extra_funcs) if scenario.scalarization_funcs: updates["scalarization_funcs"] = apply( self.base_problem.scalarization_funcs, self.scalarization_funcs, scenario.scalarization_funcs ) return self.base_problem.model_copy(update=updates) ``` #### validate_anticipation_stop ``` validate_anticipation_stop(v, info) ``` Validate that anticipation_stop keys exist in scenario_tree and values are valid variable symbols. Source code in `desdeo/problem/scenario.py` ``` @field_validator("anticipation_stop", mode="after") @classmethod def validate_anticipation_stop(cls, v, info): """Validate that anticipation_stop keys exist in scenario_tree and values are valid variable symbols.""" data = info.data valid_nodes = set(data.get("scenario_tree", {}).keys()) base_problem = data.get("base_problem") valid_variables = ( {var.symbol for var in base_problem.variables} if base_problem and base_problem.variables else set() ) # Pool variables (added to scenarios) are also valid anticipation targets. valid_variables |= {var.symbol for var in data.get("variables", ())} for node, symbols in v.items(): if node not in valid_nodes: raise ValueError(f"anticipation_stop key '{node}' not found in scenario_tree.") for symbol in symbols: if symbol not in valid_variables: raise ValueError( f"Variable symbol '{symbol}' in anticipation_stop['{node}'] " "not found in base_problem variables or the variable pool." ) return v ``` #### validate_scenario_probabilities ``` validate_scenario_probabilities(v, info) ``` Auto-inject ROOT=1.0 and verify child probabilities sum to their parent's probability. Source code in `desdeo/problem/scenario.py` ``` @field_validator("scenario_probabilities", mode="after") @classmethod def validate_scenario_probabilities(cls, v, info): """Auto-inject ROOT=1.0 and verify child probabilities sum to their parent's probability.""" if not v: return v tree: dict[str, list[str]] = info.data.get("scenario_tree", {}) v.setdefault("ROOT", 1.0) for key in v: if key not in tree: raise ValueError(f"scenario_probabilities key '{key}' not found in scenario_tree.") for parent, children in tree.items(): if not children: continue if not any(c in v for c in children): continue parent_prob = v.get(parent) if parent_prob is None: raise ValueError(f"Probability for node '{parent}' is missing.") missing = [c for c in children if c not in v] if missing: raise ValueError(f"Probabilities missing for children of '{parent}': {missing}.") child_sum = sum(v[c] for c in children) if not math.isclose(child_sum, parent_prob, rel_tol=1e-9): raise ValueError(f"Probabilities of children of '{parent}' sum to {child_sum}, expected {parent_prob}.") return v ``` #### validate_scenarios ``` validate_scenarios(v, info) ``` Validate that scenario names exist in scenario_tree and that all indices are in bounds. Source code in `desdeo/problem/scenario.py` ``` @field_validator("scenarios", mode="after") @classmethod def validate_scenarios(cls, v, info): """Validate that scenario names exist in scenario_tree and that all indices are in bounds.""" data = info.data valid_scenarios = set(data.get("scenario_tree", {}).keys()) pool_lengths = { "constants": len(data.get("constants", [])), "variables": len(data.get("variables", [])), "objectives": len(data.get("objectives", [])), "constraints": len(data.get("constraints", [])), "extra_funcs": len(data.get("extra_funcs", [])), "scalarization_funcs": len(data.get("scalarization_funcs", [])), } for scenario_name, scenario in v.items(): if scenario_name not in valid_scenarios: raise ValueError(f"Scenario '{scenario_name}' not found in scenario_tree.") for field, length in pool_lengths.items(): for symbol, idx in getattr(scenario, field).items(): if idx < 0 or idx >= length: raise ValueError( f"Index {idx} for symbol '{symbol}' in scenario '{scenario_name}.{field}' " f"is out of bounds (pool length {length})." ) return v ``` #### validate_tree_structure ``` validate_tree_structure(v) ``` Verify that scenario_tree is a valid rooted tree with ROOT as the universal ancestor. Source code in `desdeo/problem/scenario.py` ``` @field_validator("scenario_tree", mode="after") @classmethod def validate_tree_structure(cls, v): """Verify that scenario_tree is a valid rooted tree with ROOT as the universal ancestor.""" if "ROOT" not in v: raise ValueError("scenario_tree must contain a 'ROOT' key.") child_counts: dict[str, int] = {} for children in v.values(): for child in children: child_counts[child] = child_counts.get(child, 0) + 1 if "ROOT" in child_counts: raise ValueError("'ROOT' must not appear as a child of any node.") multi_parent = [n for n, c in child_counts.items() if c > 1] if multi_parent: raise ValueError(f"Nodes have more than one parent (not a tree): {sorted(multi_parent)}.") visited: set[str] = set() stack = ["ROOT"] while stack: node = stack.pop() visited.add(node) stack.extend(v.get(node, [])) unreachable = set(v) - visited if unreachable: raise ValueError(f"Nodes not reachable from ROOT: {sorted(unreachable)}.") return v ``` #### with_base_problem ``` with_base_problem( problem: Problem | None = None, validate: bool = False, **updates: dict[str, any], ) -> ScenarioModel ``` Return a new ScenarioModel with the base_problem updated. By default uses model_copy, so validators are NOT re-run. Pass `validate=True` to reconstruct via model_validate, which re-runs all field validators (including anticipation_stop checks). Only safe when the update cannot remove variables or scenario-tree nodes that validators reference. Parameters: | Name | Type | Description | Default | | ----------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | | `problem` | \`Problem | None\` | if provided, replaces the base_problem entirely. | | `validate` | `bool` | if True, reconstruct with model_validate so all validators run, which is somewhat slower. Defaults to False. | `False` | | `**updates` | `dict[str, any]` | keyword arguments forwarded to Problem.model_copy(update=...) to partially update the existing base_problem. Ignored when problem is given. | `{}` | Returns: | Type | Description | | --------------- | --------------------------------------------------- | | `ScenarioModel` | A new ScenarioModel with the modified base_problem. | Source code in `desdeo/problem/scenario.py` ``` def with_base_problem( self, problem: "Problem | None" = None, validate: bool = False, **updates: dict[str, any] ) -> "ScenarioModel": """Return a new ScenarioModel with the base_problem updated. By default uses model_copy, so validators are NOT re-run. Pass ``validate=True`` to reconstruct via model_validate, which re-runs all field validators (including anticipation_stop checks). Only safe when the update cannot remove variables or scenario-tree nodes that validators reference. Args: problem: if provided, replaces the base_problem entirely. validate: if True, reconstruct with model_validate so all validators run, which is somewhat slower. Defaults to False. **updates: keyword arguments forwarded to Problem.model_copy(update=...) to partially update the existing base_problem. Ignored when ``problem`` is given. Returns: A new ScenarioModel with the modified base_problem. """ new_base = problem if problem is not None else self.base_problem.model_copy(update=updates) if validate: return type(self).model_validate(self.model_dump() | {"base_problem": new_base}) return self.model_copy(update={"base_problem": new_base}) ``` ## JSON parser ### desdeo.problem.json_parser Defines a parser to parse multiobjective optimziation problems defined in a JSON format. #### FormatEnum Bases: `StrEnum` Enumerates the supported formats the JSON format may be parsed to. Source code in `desdeo/problem/json_parser.py` ``` class FormatEnum(StrEnum): """Enumerates the supported formats the JSON format may be parsed to.""" polars = "polars" pyomo = "pyomo" sympy = "sympy" gurobipy = "gurobipy" cvxpy = "cvxpy" ``` #### MathParser A class to instantiate MathJSON parsers. Parses MathJSON expressions to polars, pyomo, sympy, gurobipy, or cvxpy expressions. Source code in `desdeo/problem/json_parser.py` ``` class MathParser: """A class to instantiate MathJSON parsers. Parses MathJSON expressions to polars, pyomo, sympy, gurobipy, or cvxpy expressions. """ def __init__(self, to_format: FormatEnum = "polars"): # noqa: C901 """Create a parser instance for parsing MathJSON notation into polars expressions. Args: to_format (FormatEnum, optional): to which format a JSON representation should be parsed to. Defaults to "polars". """ # Define operator names. Change these when the name is altered in the JSON format. # Basic arithmetic operators self.NEGATE: str = "Negate" self.ADD: str = "Add" self.SUB: str = "Subtract" self.MUL: str = "Multiply" self.DIV: str = "Divide" # Vector and matrix operations self.MATMUL: str = "MatMul" self.SUM: str = "Sum" self.RANDOM_ACCESS = "At" self.EXTRACT: str = "Extract" self.EXCLUDE: str = "Exclude" self.TUPLE: str = "Tuple" # Exponentation and logarithms self.EXP: str = "Exp" self.LN: str = "Ln" self.LB: str = "Lb" self.LG: str = "Lg" self.LOP: str = "LogOnePlus" self.SQRT: str = "Sqrt" self.SQUARE: str = "Square" self.POW: str = "Power" # Rounding operators self.ABS: str = "Abs" self.CEIL: str = "Ceil" self.FLOOR: str = "Floor" # Trigonometric operations self.ARCCOS: str = "Arccos" self.ARCCOSH: str = "Arccosh" self.ARCSIN: str = "Arcsin" self.ARCSINH: str = "Arcsinh" self.ARCTAN: str = "Arctan" self.ARCTANH: str = "Arctanh" self.COS: str = "Cos" self.COSH: str = "Cosh" self.SIN: str = "Sin" self.SINH: str = "Sinh" self.TAN: str = "Tan" self.TANH: str = "Tanh" # Comparison operators self.EQUAL: str = "Equal" self.GREATER: str = "Greater" self.GE: str = "GreaterEqual" self.LESS: str = "Less" self.LE: str = "LessEqual" self.NE: str = "NotEqual" # Other operators self.MAX: str = "Max" self.MIN: str = "Min" self.RATIONAL: str = "Rational" self.literals = int | float def _collect_indices(raw_indices: tuple, n: int) -> list[int]: """Collect 0-based indices from a sequence of raw Extract/Exclude specs. Args: raw_indices: the index arguments passed to Extract or Exclude. Each element is either a plain number (single 1-based index) or a tuple ``(start, stop[, step])``. Positive values count from the front; negative values count from the back (e.g. ``-1`` is the last element). n: total length of the array being indexed. Required to resolve negative indices and to clamp out-of-range values. """ def _to_zero(i1: int) -> int: # Convert a 1-based (positive) or end-relative (negative) index to 0-based. return (i1 - 1) if i1 > 0 else (n + i1) indices = [] for spec in raw_indices: if isinstance(spec, tuple): start = _to_zero(int(spec[0])) stop = _to_zero(int(spec[1])) step = int(spec[2]) if len(spec) >= 3 else (1 if stop >= start else -1) # noqa: PLR2004 rng = range(start, stop + 1, step) if step > 0 else range(start, stop - 1, step) indices.extend(i for i in rng if 0 <= i < n) else: zero = _to_zero(int(spec)) if 0 <= zero < n: indices.append(zero) return indices def _extract_from_array(arr, *raw_indices): arr = np.asarray(arr) idx = _collect_indices(raw_indices, arr.shape[0]) return arr[idx].tolist() if idx else [] def _exclude_from_array(arr, *raw_indices): arr = np.asarray(arr) n = arr.shape[0] excluded = set(_collect_indices(raw_indices, n)) keep = [i for i in range(n) if i not in excluded] return arr[keep].tolist() if keep else [] def _polars_extract(expr, *raw_indices): def _fn(acc): arr = acc.to_numpy() if arr.ndim > 1: idx = _collect_indices(raw_indices, arr.shape[-1]) result = arr[..., idx] if idx else np.empty((*arr.shape[:-1], 0), dtype=arr.dtype) else: result = _extract_from_array(arr, *raw_indices) return pl.Series(values=result.tolist()) return to_expr(expr).map_batches(_fn) def _polars_exclude(expr, *raw_indices): def _fn(acc): arr = acc.to_numpy() if arr.ndim > 1: n = arr.shape[-1] excluded = set(_collect_indices(raw_indices, n)) keep = [i for i in range(n) if i not in excluded] result = arr[..., keep] if keep else np.empty((*arr.shape[:-1], 0), dtype=arr.dtype) else: result = _exclude_from_array(arr, *raw_indices) return pl.Series(values=result.tolist()) return to_expr(expr).map_batches(_fn) def _not_impl_extract(*_args): raise NotImplementedError("'Extract' is not implemented for this backend.") def _not_impl_exclude(*_args): raise NotImplementedError("'Exclude' is not implemented for this backend.") def to_expr(x: self.literals | pl.Expr): # type: ignore """Helper function to convert literals to polars expressions.""" return pl.lit(x) if isinstance(x, self.literals) else x def to_sympy_expr(x): return sp.sympify(x, evaluate=False) if isinstance(x, self.literals) else x def gp_error(): msg = "The gurobipy model format only supports linear and quadratic expressions." ParserError(msg) def _polars_pow(base, exponent): base = to_expr(base) exponent = to_expr(exponent) # Detect a constant exponent (the operands have already been parsed to polars # expressions, so a literal arrives as pl.lit(...)). A constant exponent lets us # apply the power via a unary UDF so polars can infer the shape-preserving return # dtype: native `**` does not work on array columns, and an N-ary UDF nested in # other expressions cannot be inferred by polars >=1.31. try: exponent_value = pl.select(exponent).item() except Exception: exponent_value = None if exponent_value is not None: return base.map_batches( lambda series, exp=exponent_value: pl.Series(values=np.power(series.to_numpy(), exp)) ) # Non-constant exponent (rare): native power, which works for scalar operands. return base**exponent def _polars_reduce_unary(expr, ufunc): def _map_function(acc, ufunc=ufunc): # Unary math functions (e.g. log, arctanh) can legitimately hit domain edges such as # log(0) or arctanh(+-1); the resulting inf/nan is the intended evaluation result, so # silence the benign numpy warnings. with np.errstate(divide="ignore", invalid="ignore"): return pl.Series(values=ufunc(acc.to_numpy())) return to_expr(expr).map_batches(_map_function) def _polars_reduce_matmul(*exprs): # Numpy matmul (row-vector dot product OR matrix product) via an N-ary UDF. # No return dtype is declared: polars infers it from a sample, which works # because the surrounding +,-,*,/ are native expressions (not UDFs), so this # UDF is never nested inside another un-inferrable UDF. def _map_function(series_list): acc = series_list[0].to_numpy() for series in series_list[1:]: x = series.to_numpy() if acc.ndim == 2 and x.ndim == 2: # noqa: PLR2004 # row vectors -> per-row dot product (polars has no "column" vectors) acc = np.einsum("ij,ij->i", acc, x, optimize=True) else: acc = np.matmul(acc, x) return pl.Series(values=acc) return pl.map_batches(exprs=[to_expr(expr) for expr in exprs], function=_map_function) def _polars_summation(expr): """Polars matrix summation.""" def _map_function(acc): acc_numpy = acc.to_numpy() return pl.Series(values=np.sum(acc_numpy, axis=tuple(range(1, acc_numpy.ndim)))) return to_expr(expr).map_batches(_map_function) def _polars_random_access(expr, *indices): """Polars tensor random access.""" for index in indices: expr = expr.arr.get(index - 1) # 1 indexing assumed in JSON format return expr def _polars_generic_apply(a, b): pass polars_env = { # Define the operations for the different operators. # Basic arithmetic operations self.NEGATE: lambda x: _polars_reduce_unary(x, np.negative), self.ADD: lambda *args: reduce(lambda a, b: to_expr(a) + to_expr(b), args), self.SUB: lambda *args: reduce(lambda a, b: to_expr(a) - to_expr(b), args), self.MUL: lambda *args: reduce(lambda a, b: to_expr(a) * to_expr(b), args), self.DIV: lambda *args: reduce(lambda a, b: to_expr(a) / to_expr(b), args), # Vector and matrix operations self.MATMUL: _polars_reduce_matmul, self.SUM: lambda x: _polars_summation(x), self.RANDOM_ACCESS: _polars_random_access, self.EXTRACT: _polars_extract, self.EXCLUDE: _polars_exclude, # Exponentiation and logarithms self.EXP: lambda x: _polars_reduce_unary(x, np.exp), self.LN: lambda x: _polars_reduce_unary(x, np.log), self.LB: lambda x: _polars_reduce_unary(x, np.log2), self.LG: lambda x: _polars_reduce_unary(x, np.log10), self.LOP: lambda x: _polars_reduce_unary(x, np.log1p), self.SQRT: lambda x: _polars_reduce_unary(x, np.sqrt), self.SQUARE: lambda x: _polars_reduce_unary(x, lambda y: np.power(y, 2)), self.POW: lambda *args: reduce(_polars_pow, args), # Trigonometric operations self.ARCCOS: lambda x: _polars_reduce_unary(x, np.arccos), self.ARCCOSH: lambda x: _polars_reduce_unary(x, np.arccosh), self.ARCSIN: lambda x: _polars_reduce_unary(x, np.arcsin), self.ARCSINH: lambda x: _polars_reduce_unary(x, np.arcsinh), self.ARCTAN: lambda x: _polars_reduce_unary(x, np.arctan), self.ARCTANH: lambda x: _polars_reduce_unary(x, np.arctanh), self.COS: lambda x: _polars_reduce_unary(x, np.cos), self.COSH: lambda x: _polars_reduce_unary(x, np.cosh), self.SIN: lambda x: _polars_reduce_unary(x, np.sin), self.SINH: lambda x: _polars_reduce_unary(x, np.sinh), self.TAN: lambda x: _polars_reduce_unary(x, np.tan), self.TANH: lambda x: _polars_reduce_unary(x, np.tanh), # Rounding operations self.ABS: lambda x: _polars_reduce_unary(x, np.abs), self.CEIL: lambda x: _polars_reduce_unary(x, np.ceil), self.FLOOR: lambda x: _polars_reduce_unary(x, np.floor), # Other operations self.RATIONAL: lambda lst: reduce(lambda x, y: x / y, lst), # Not supported self.MAX: lambda *args: reduce(lambda x, y: pl.max_horizontal(to_expr(x), to_expr(y)), args), self.MIN: lambda *args: reduce(lambda x, y: pl.min_horizontal(to_expr(x), to_expr(y)), args), } def _pyomo_negate(x): """Negates the given operand.""" def _expr_negate_rule(x): def _inner(_, *indices): return -x[indices] return _inner def _negate(x): # check if operand in indexed if hasattr(x, "index_set") and x.is_indexed(): # indexed, return new pyomo expression expr = pyomo.Expression(x.index_set(), rule=_expr_negate_rule(x)) expr.construct() return expr # not indexed, just regular negate return -x return _negate(x) def _pyomo_pow(base, exp): """Implements a power operator compatible with Pyomo expressions.""" def _expr_pow_rule(base, exp): def _inner(_, *indices): return base[indices] ** exp return _inner def _pow(base, exp=exp): # check if operand in indexed if hasattr(base, "index_set") and base.is_indexed(): # indexed, return new pyomo expression expr = pyomo.Expression(base.index_set(), rule=_expr_pow_rule(base, exp)) expr.construct() return expr # not indexed, just regular power return base**exp return _pow(base, exp) def _pyomo_unary(x, op): """Implements unary operators to work with indexed expressions.""" def _expr_rule(x, op): def _inner(_, *indices, op=op): return op(x[indices]) return _inner def _op(x, op): # check if operand in indexed if hasattr(x, "index_set") and x.is_indexed(): # indexed, return new pyomo expression expr = pyomo.Expression(x.index_set(), rule=_expr_rule(x, op)) expr.construct() return expr # not indexed, just regular power return op(x) return _op(x, op) def _pyomo_addition(*args, subtraction=False): """Add (subtract) scalars or tensors to (from) each other.""" def _expr_matrix_addition_rule(x, y, subtraction=subtraction): def _inner(_, *args): return x[*args] + y[*args] if not subtraction else x[*args] - y[*args] return _inner def _expr_elementwise_with_single_indexed(indexed, not_indexed, subtraction=subtraction): def _inner(_, *indices): return (indexed[indices] + not_indexed) if not subtraction else (indexed[indices] - not_indexed) return _inner def _add(x, y, subtraction=subtraction): # if both are indexed, try matrix addition if (hasattr(x, "index_set") and x.is_indexed()) and (hasattr(y, "index_set") and y.is_indexed()): # try matrix addition # check that the dimensions of x and y matches x_idx, y_idx = x.index_set(), y.index_set() if x_idx.dimen != y_idx.dimen or len(x_idx) != len(y_idx): msg = ( f"The shapes of x ({x_idx.dimen}D, len={len(x_idx)}) and " f"y ({y_idx.dimen}D, len={len(y_idx)}) must match for matrix addition." ) raise ParserError(msg) expr = pyomo.Expression( x.index_set(), rule=_expr_matrix_addition_rule(x, y, subtraction=subtraction) ) expr.construct() return expr # if neither is indexed, do normal addition if not (hasattr(x, "index_set") and x.is_indexed()) and not ( hasattr(y, "index_set") and y.is_indexed() ): if not subtraction: # try regular addition return x + y # try regular subtraction return x - y # x is indexed, y is not if (hasattr(x, "index_set")) and x.is_indexed(): expr = pyomo.Expression( x.index_set(), rule=_expr_elementwise_with_single_indexed(x, y, subtraction=subtraction) ) expr.construct() return expr # if y is indexed, x is not if (hasattr(y, "index_set")) and y.is_indexed(): expr = pyomo.Expression( y.index_set(), rule=_expr_elementwise_with_single_indexed(y, x, subtraction=subtraction) ) expr.construct() return expr # if only one of the operands is indexed, then addition is not supported. Throw error. msg = "For addition, both operands must be either scalars or matrices with matching dimensions." raise ParserError(msg) return reduce(_add, args) def _pyomo_subtraction(*args): return _pyomo_addition(*args, subtraction=True) def _pyomo_multiply(*args, division=False): """Multiply tensor with a scalar.""" def _expr_multiply_with_scalar_rule(scalar_value, to_multiply, division=division): def _inner(_, *indices): return to_multiply[indices] * scalar_value if not division else to_multiply[indices] / scalar_value return _inner def _expr_matrix_multiply_rule(x, y, division=division): def _inner(_, *args): return x[*args] * y[*args] if not division else x[*args] / y[*args] return _inner def _multiply(x, y, division=division): if not hasattr(x, "is_indexed") and not hasattr(y, "is_indexed"): # x and y are scalars return x * y if not division else x / y # check if x or y is scalar if ( hasattr(x, "is_indexed") and x.is_indexed() and x.dim() > 0 and (not hasattr(y, "is_indexed") or not y.is_indexed() or (y.is_indexed() and y.dim() == 0)) ): # x is a tensor, y is scalar expr = pyomo.Expression( x.index_set(), rule=_expr_multiply_with_scalar_rule(y, x, division=division) ) expr.construct() return expr if ( hasattr(y, "is_indexed") and y.is_indexed() and y.dim() > 0 and (not hasattr(x, "is_indexed") or not x.is_indexed() or (x.is_indexed() and x.dim() == 0)) ): # y is a tensor, x is scalar expr = pyomo.Expression( y.index_set(), rule=_expr_multiply_with_scalar_rule(x, y, division=division) ) expr.construct() return expr # check if both are indexed if hasattr(x, "index_set") and hasattr(y, "index_set"): # both are indexed, neither is a scalar, check dims and sized, if match, # multiply together element-wise if x.index_set() != y.index_set(): msg = ( f"The dimensions of x {x.index_set().set_tuple} must match that" f" of y {y.index_set().set_tuple} for element-wise matrix multiplication." ) raise ParserError(msg) expr = pyomo.Expression(x.index_set(), rule=_expr_matrix_multiply_rule(x, y, division=division)) expr.construct() return expr # both are scalars return x * y if not division else x / y return reduce(_multiply, args) def _pyomo_division(*args): return _pyomo_multiply(*args, division=True) def _pyomo_matrix_multiplication(*args): """Multiply two matrices together.""" def _expr_matmul_rule(mat_a, mat_b, j_indices): def _inner(_, i_index, k_index): return sum(mat_a[i_index, j] * mat_b[j, k_index] for j in j_indices) return _inner def _matmul(mat_a, mat_b): if not (hasattr(mat_a, "is_indexed") and mat_a.is_indexed()) or not ( hasattr(mat_b, "is_indexed") and mat_b.is_indexed() ): # either mat_a or mat_b is not tensor msg = "Either mat_a or mat_b, or both, is not indexed. Cannot perform matrix multiplication." raise ParserError(msg) # check for regular vectors, then do dot product if mat_a.dim() == 1 and mat_b.dim() == 1: if (len_a := len(mat_a.index_set())) != (len_b := len(mat_b.index_set())): msg = ( "For dot product, the sizes of the vectors must match." f" Sizes mat_a = {len_a} and mat_b = {len_b}." ) raise ParserError(msg) return pyomo.sum_product(mat_a, mat_b, index=mat_a.index_set()) # assuming mat_a has dimensions i,j; and mat_b j,k; # then the j dimension is squeezed and the i and k dimensions are kept. # check that we are dealing with matrices min_dimension = 2 if ( not hasattr(mat_a.index_set(), "set_tuple") or len(mat_a.index_set().set_tuple) < min_dimension ) or (not hasattr(mat_b.index_set(), "set_tuple") and len(mat_b.index_set().set_tuple) < min_dimension): msg = "Both mat_a and mat_b must have at least two dimensions." raise ParserError(msg) # check that the outer dimensions (the one to be squeezed) matches if len(mat_a.index_set().set_tuple[-1]) != len(mat_b.index_set().set_tuple[0]): msg = ( f"The last dimension size of mat_a ({mat_a.index_set().set_tuple[-1]}) must " f"match the first dimension of mat_b ({mat_b.index_set().set_tuple[0]})" ) raise ParserError(msg) expr = pyomo.Expression( mat_a.index_set().set_tuple[0], mat_b.index_set().set_tuple[1], rule=_expr_matmul_rule(mat_a, mat_b, mat_a.index_set().set_tuple[1]), ) expr.construct() return expr return reduce(_matmul, args) def _pyomo_summation(summand): """Sum an indexed Pyomo object.""" return pyomo.sum_product(summand, index=summand.index_set()) def _pyomo_random_access(indexed, *indices): return indexed[*indices] def _pyomo_extract(indexed, *raw_indices): if not (hasattr(indexed, "index_set") and indexed.is_indexed()): msg = "'Extract' requires an indexed Pyomo expression." raise ParserError(msg) all_indices = sorted(indexed.index_set()) n = len(all_indices) positions = _collect_indices(raw_indices, n) selected = [all_indices[p] for p in positions] new_set = pyomo.RangeSet(1, len(selected)) idx_map = {i + 1: sel for i, sel in enumerate(selected)} expr = pyomo.Expression(new_set, rule=lambda _, i: indexed[idx_map[i]]) expr.construct() return expr def _pyomo_exclude(indexed, *raw_indices): if not (hasattr(indexed, "index_set") and indexed.is_indexed()): msg = "'Exclude' requires an indexed Pyomo expression." raise ParserError(msg) all_indices = sorted(indexed.index_set()) n = len(all_indices) excluded_pos = set(_collect_indices(raw_indices, n)) keep = [all_indices[p] for p in range(n) if p not in excluded_pos] new_set = pyomo.RangeSet(1, len(keep)) idx_map = {i + 1: k for i, k in enumerate(keep)} expr = pyomo.Expression(new_set, rule=lambda _, i: indexed[idx_map[i]]) expr.construct() return expr pyomo_env = { # Define the operations for the different operators. # Basic arithmetic operations self.NEGATE: _pyomo_negate, self.ADD: _pyomo_addition, self.SUB: _pyomo_subtraction, self.MUL: _pyomo_multiply, self.DIV: _pyomo_division, # Vector and matrix operations self.MATMUL: _pyomo_matrix_multiplication, self.SUM: _pyomo_summation, self.RANDOM_ACCESS: _pyomo_random_access, self.EXTRACT: _pyomo_extract, self.EXCLUDE: _pyomo_exclude, # Exponentiation and logarithms self.EXP: lambda x: _pyomo_unary(x, pyomo.exp), self.LN: lambda x: _pyomo_unary(x, pyomo.log), self.LB: lambda x: _pyomo_unary( x, lambda x: pyomo.log(x) / pyomo.log(2) ), # change of base, pyomo has no log2 self.LG: lambda x: _pyomo_unary(x, pyomo.log10), self.LOP: lambda x: _pyomo_unary(x, lambda x: pyomo.log(x + 1)), self.SQRT: lambda x: _pyomo_unary(x, pyomo.sqrt), self.SQUARE: lambda x: _pyomo_pow(x, 2), self.POW: lambda x, y: _pyomo_pow(x, y), # Trigonometric operations self.ARCCOS: lambda x: _pyomo_unary(x, pyomo.acos), self.ARCCOSH: lambda x: _pyomo_unary(x, pyomo.acosh), self.ARCSIN: lambda x: _pyomo_unary(x, pyomo.asin), self.ARCSINH: lambda x: _pyomo_unary(x, pyomo.asinh), self.ARCTAN: lambda x: _pyomo_unary(x, pyomo.atan), self.ARCTANH: lambda x: _pyomo_unary(x, pyomo.atanh), self.COS: lambda x: _pyomo_unary(x, pyomo.cos), self.COSH: lambda x: _pyomo_unary(x, pyomo.cosh), self.SIN: lambda x: _pyomo_unary(x, pyomo.sin), self.SINH: lambda x: _pyomo_unary(x, pyomo.sinh), self.TAN: lambda x: _pyomo_unary(x, pyomo.tan), self.TANH: lambda x: _pyomo_unary(x, pyomo.tanh), # Rounding operations self.ABS: lambda x: _pyomo_unary(x, abs), self.CEIL: lambda x: _pyomo_unary(x, pyomo.ceil), self.FLOOR: lambda x: _pyomo_unary(x, pyomo.floor), # Other operations self.RATIONAL: lambda lst: reduce(lambda x, y: x / y, lst), # not supported # probably a better idea to reformulate expressions with a max when utilized with pyomo # self.MAX: lambda *args: reduce(lambda x, y: _PyomoMax((x, y)), args), self.MAX: lambda *args: _PyomoMax(args), self.MIN: lambda *args: _PyomoMin(args), } def _sympy_matmul(*args): """Sympy matrix multiplication.""" msg = ( "Matrix multiplication '@' has not been implemented for the Sympy parser yet. Feel free to contribute!" ) raise NotImplementedError(msg) def _sympy_summation(summand): """Sympy matrix summation.""" msg = "Matrix summation 'Sum' has not been implemented for the Sympy parser yet. Feel free to contribute!" raise NotImplementedError(msg) def _sympy_random_access(*args): msg = ( "Tensor random access with 'At' has not been implemented for the Sympy parser yet. " "Feel free to contribute!" ) raise NotImplementedError(msg) sympy_env = { # Basic arithmetic operations self.NEGATE: lambda x: -to_sympy_expr(x), self.ADD: lambda *args: reduce(lambda x, y: to_sympy_expr(x) + to_sympy_expr(y), args), self.SUB: lambda *args: reduce(lambda x, y: to_sympy_expr(x) - to_sympy_expr(y), args), self.MUL: lambda *args: reduce(lambda x, y: to_sympy_expr(x) * to_sympy_expr(y), args), self.DIV: lambda *args: reduce(lambda x, y: to_sympy_expr(x) / to_sympy_expr(y), args), # Vector and matrix operations self.MATMUL: _sympy_matmul, self.SUM: _sympy_summation, self.RANDOM_ACCESS: _sympy_random_access, self.EXTRACT: _not_impl_extract, self.EXCLUDE: _not_impl_exclude, # Exponentiation and logarithms self.EXP: lambda x: sp.exp(to_sympy_expr(x)), self.LN: lambda x: sp.log(to_sympy_expr(x)), self.LB: lambda x: sp.log(to_sympy_expr(x), 2), self.LG: lambda x: sp.log(to_sympy_expr(x), 10), self.LOP: lambda x: sp.log(1 + to_sympy_expr(x)), self.SQRT: lambda x: sp.sqrt(to_sympy_expr(x)), self.SQUARE: lambda x: to_sympy_expr(x) ** 2, self.POW: lambda x, y: to_sympy_expr(x) ** to_sympy_expr(y), # Trigonometric operations self.SIN: lambda x: sp.sin(to_sympy_expr(x)), self.COS: lambda x: sp.cos(to_sympy_expr(x)), self.TAN: lambda x: sp.tan(to_sympy_expr(x)), self.ARCSIN: lambda x: sp.asin(to_sympy_expr(x)), self.ARCCOS: lambda x: sp.acos(to_sympy_expr(x)), self.ARCTAN: lambda x: sp.atan(to_sympy_expr(x)), # Hyperbolic functions self.SINH: lambda x: sp.sinh(to_sympy_expr(x)), self.COSH: lambda x: sp.cosh(to_sympy_expr(x)), self.TANH: lambda x: sp.tanh(to_sympy_expr(x)), self.ARCSINH: lambda x: sp.asinh(to_sympy_expr(x)), self.ARCCOSH: lambda x: sp.acosh(to_sympy_expr(x)), self.ARCTANH: lambda x: sp.atanh(to_sympy_expr(x)), # Other self.ABS: lambda x: sp.Abs(to_sympy_expr(x)), self.CEIL: lambda x: sp.ceiling(to_sympy_expr(x)), self.FLOOR: lambda x: sp.floor(to_sympy_expr(x)), # Note: Max and Min in sympy take any number of arguments self.MAX: lambda *args: sp.Max(*args), self.MIN: lambda *args: sp.Min(*args), # Rational numbers, for now assuming two-element list for numerator and denominator self.RATIONAL: lambda x, y: sp.Rational(x, y), } def _gurobipy_multiply(*args): """Multiply, promoting scalar gp.Var * ndarray to MLinExpr via MVar.fromlist.""" def _mul(a, b): if isinstance(a, gp.Var) and isinstance(b, np.ndarray): return gp.MVar.fromlist([a]) * b if isinstance(b, gp.Var) and isinstance(a, np.ndarray): return gp.MVar.fromlist([b]) * a return a * b return reduce(_mul, args) def _gurobipy_matmul(*args): """Gurobipy matrix multiplication.""" def _matmul(a, b): if isinstance(a, list): a = np.array(a) if isinstance(b, list): b = np.array(b) return a @ b return reduce(_matmul, args) def _gurobipy_summation(summand): """Gurobipy matrix summation.""" def _sum(summand): if isinstance(summand, list): summand = np.array(summand) return summand.sum() return _sum(summand) def _gurobipy_random_access(indexed, *indices): # 1-based indexing assumed in JSON format; convert to 0-based for Python/numpy/gp.MVar zero_based = tuple(int(i) - 1 for i in indices) if len(zero_based) == 1: return indexed[zero_based[0]] return indexed[zero_based] def _gurobipy_extract(arr, *raw_indices): idx = _collect_indices(raw_indices, arr.shape[0]) return arr[idx] def _gurobipy_exclude(arr, *raw_indices): n = arr.shape[0] excluded = set(_collect_indices(raw_indices, n)) keep = [i for i in range(n) if i not in excluded] return arr[keep] gurobipy_env = { # Define the operations for the different operators. # Basic arithmetic operations self.NEGATE: lambda x: -x, self.ADD: lambda *args: reduce(lambda x, y: x + y, args), self.SUB: lambda *args: reduce(lambda x, y: x - y, args), self.MUL: _gurobipy_multiply, self.DIV: lambda *args: reduce(lambda x, y: x / y, args), # Vector and matrix operations self.MATMUL: _gurobipy_matmul, self.SUM: _gurobipy_summation, self.RANDOM_ACCESS: _gurobipy_random_access, self.EXTRACT: _gurobipy_extract, self.EXCLUDE: _gurobipy_exclude, # Exponentiation and logarithms # it would be possible to implement some of these with the special functions that # gurobi has to offer, but they would only work under specific circumstances self.EXP: lambda x: gp_error(), self.LN: lambda x: gp_error(), self.LB: lambda x: gp_error(), self.LG: lambda x: gp_error(), self.LOP: lambda x: gp_error(), self.SQRT: lambda x: gp_error(), self.SQUARE: lambda x: x**2, self.POW: lambda x, y: x**y, # this will likely cause an error at some point for most y # Trigonometric operations # it would be possible to implement some of these with the special functions that # gurobi has to offer, but they would only work under specific circumstances self.ARCCOS: lambda x: gp_error(), self.ARCCOSH: lambda x: gp_error(), self.ARCSIN: lambda x: gp_error(), self.ARCSINH: lambda x: gp_error(), self.ARCTAN: lambda x: gp_error(), self.ARCTANH: lambda x: gp_error(), self.COS: lambda x: gp_error(), self.COSH: lambda x: gp_error(), self.SIN: lambda x: gp_error(), self.SINH: lambda x: gp_error(), self.TAN: lambda x: gp_error(), self.TANH: lambda x: gp_error(), # Rounding operations self.ABS: lambda x: gp.abs_(x), self.CEIL: lambda x: gp_error(), self.FLOOR: lambda x: gp_error(), # Other operations self.RATIONAL: lambda lst: reduce(lambda x, y: x / y, lst), # not supported self.MAX: lambda *args: gp.max_(args), ## OBS! max and min are unsupported, but left here for reasons self.MIN: lambda *args: gp.min_(args), } def _cvxpy_error(): msg = "The cvxpy model format only supports linear and quadratic expressions." return lambda x: (_ for _ in ()).throw(ParserError(msg)) def _cvxpy_matmul(*args): """CVXPY matrix multiplication.""" def _matmul(a, b): if isinstance(a, list): a = np.array(a) if isinstance(b, list): b = np.array(b) return a @ b return reduce(_matmul, args) def _cvxpy_summation(summand): """CVXPY matrix summation.""" def _sum(summand): if isinstance(summand, list): summand = np.array(summand) return cp.sum(summand) return _sum(summand) def _cvxpy_random_access(indexed, *indices): zero_based = tuple(int(i) - 1 for i in indices) if len(zero_based) == 1: return indexed[zero_based[0]] return indexed[zero_based] def _cvxpy_extract(expr, *raw_indices): n = expr.shape[0] idx = _collect_indices(raw_indices, n) return expr[idx] def _cvxpy_exclude(expr, *raw_indices): n = expr.shape[0] excluded = set(_collect_indices(raw_indices, n)) keep = [i for i in range(n) if i not in excluded] return expr[keep] cvxpy_env = { # Define the operations for the different operators. # Basic arithmetic operations self.NEGATE: lambda x: -x, self.ADD: lambda *args: reduce(lambda x, y: x + y, args), self.SUB: lambda *args: reduce(lambda x, y: x - y, args), self.MUL: lambda *args: reduce(lambda x, y: x * y, args), self.DIV: lambda *args: reduce(lambda x, y: x / y, args), # Vector and matrix operations self.MATMUL: _cvxpy_matmul, self.SUM: _cvxpy_summation, self.RANDOM_ACCESS: _cvxpy_random_access, self.EXTRACT: _cvxpy_extract, self.EXCLUDE: _cvxpy_exclude, # Exponentiation and logarithms # CVXPY supports some of these via special functions, but with restrictions self.EXP: lambda x: cp.exp(x), self.LN: lambda x: cp.log(x), self.LB: lambda x: cp.log(x) / np.log(2), self.LG: lambda x: cp.log(x) / np.log(10), self.LOP: lambda x: cp.log1p(x), self.SQRT: lambda x: cp.sqrt(x), self.SQUARE: lambda x: cp.square(x), self.POW: lambda x, y: x**y, # may cause errors for non-integer powers # Trigonometric operations - CVXPY supports these self.ARCCOS: lambda x: cp.arccos(x), self.ARCCOSH: lambda x: cp.arccosh(x), self.ARCSIN: lambda x: cp.arcsin(x), self.ARCSINH: lambda x: cp.arcsinh(x), self.ARCTAN: lambda x: cp.arctan(x), self.ARCTANH: lambda x: cp.arctanh(x), self.COS: lambda x: cp.cos(x), self.COSH: lambda x: cp.cosh(x), self.SIN: lambda x: cp.sin(x), self.SINH: lambda x: cp.sinh(x), self.TAN: lambda x: cp.tan(x), self.TANH: lambda x: cp.tanh(x), # Rounding operations self.ABS: lambda x: cp.abs(x), self.CEIL: lambda x: cp.ceil(x), self.FLOOR: lambda x: cp.floor(x), # Other operations self.RATIONAL: lambda lst: reduce(lambda x, y: x / y, lst), self.MAX: lambda *args: cp.max(cp.stack(args, axis=0), axis=0), self.MIN: lambda *args: cp.min(cp.stack(args, axis=0), axis=0), } match to_format: case FormatEnum.polars: self.env = polars_env self.parse = self._parse_to_polars case FormatEnum.pyomo: self.env = pyomo_env self.parse = self._parse_to_pyomo case FormatEnum.sympy: self.env = sympy_env self.parse = self._parse_to_sympy case FormatEnum.gurobipy: self.env = gurobipy_env self.parse = self._parse_to_gurobipy case FormatEnum.cvxpy: self.env = cvxpy_env self.parse = self._parse_to_cvxpy case _: msg = f"Given target format {to_format} not supported. Must be one of {FormatEnum}." raise ParserError(msg) def _parse_to_polars(self, expr: list | str | int | float) -> pl.Expr: """Recursively parses JSON math expressions and returns a polars expression. Arguments: expr (list): A list with a Polish notation expression that describes a, e.g., ["Multiply", ["Sqrt", 2], "x2"] Raises: ParserError: when a unsupported operator type is encountered. Returns: pl.Expr: A polars expression that may be evaluated further. """ if isinstance(expr, pl.Expr): # Terminal case: polars expression return expr if isinstance(expr, str): # Terminal case: str expression (represents a column name) return pl.col(expr) if isinstance(expr, self.literals): # Terminal case: numeric literal return pl.lit(expr) if isinstance(expr, list): if len(expr) == 1 and isinstance(expr[0], str | self.literals): # Terminal case, single symbol expression or literal if isinstance(expr[0], str): return pl.col(expr) # just a literal return pl.lit(expr[0]) # Extract/Exclude: index args must stay as raw Python values, not polars expressions. if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self.parse(expr[1]) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self.parse(e) for e in expr[1:]] if isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) # else, assume the list contents are parseable expressions return [self.parse(e) for e in expr] msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) def _parse_to_pyomo( self, expr: list | str | int | float | pyomo.Expression, model: pyomo.Model ) -> pyomo.Expression: """Parses the MathJSON format recursively into a Pyomo expression. Args: expr (list | str | int | float): a list with a Polish notation expression that describes a, e.g., ["Multiply", ["Sqrt", 2], "x2"] model (pyomo.Model): a pyomo model with the symbols defined appearing in the expression. E.g., "x2" -> model.x2 must be defined. Raises: ParserError: when a unsupported operator type is encountered. Returns: pyomo.Expression: returns a pyomo expression equivalent to the original expressions. """ if isinstance(expr, pyomo.Expression): # Terminal case: pyomo expression return expr if isinstance(expr, str): # Terminal case: str expression, represent a variable or expression return getattr(model, expr) if isinstance(expr, self.literals): # Terminal case: numeric literal return expr if isinstance(expr, list): if len(expr) == 1 and isinstance(expr[0], str | self.literals): # Terminal case, single symbol expression or literal if isinstance(expr[0], str): return getattr(model, expr[0]) # just a literal return pyomo.Expression(expr=expr[0]) if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self._parse_to_pyomo(expr[1], model) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self._parse_to_pyomo(e, model) for e in expr[1:]] if isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) # else, assume the list contents are parseable expressions return [self._parse_to_pyomo(e, model) for e in expr] msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) def _parse_to_sympy(self, expr: list | str | int | float | sp.Basic) -> sp.Basic: """Parse the MathJSON format recursively into a sympy expression. Args: expr (list | str | int | float | sp.Basic): base call should be a list in Polish notation representing a mathematical expression. Recursion calls can be of various types. Raises: ParserError: when a unsupported operator type is encountered. Returns: sp.Basic: a sympy expression that represents the original mathematical expression in the supplied MathJSON format. """ if isinstance(expr, sp.Basic): # Terminal case: sympy expression return expr if isinstance(expr, str): # Terminal case: represents a variable return sp.sympify(expr, evaluate=False) if isinstance(expr, self.literals): # Terminal case: numeric literal return sp.sympify(expr, evaluate=False) if isinstance(expr, list): if len(expr) == 1 and isinstance(expr[0], str | self.literals): # Terminal case, single symbol expression or literal return sp.sympify(expr[0], evaluate=False) if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self.parse(expr[1]) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self.parse(e) for e in expr[1:]] if isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) # else, assume the list contents are parseable expressions return [self.parse(e) for e in expr] msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) def _parse_to_gurobipy( self, expr: list | str | int | float, callback: Callable[[str], gpexpression | int | float] ) -> gpexpression | int | float: """Parses the MathJSON format recursively into a gurobipy expression. Gurobi only fundamentally supports linear and quadratic expressions, and this parser does not check that the inputs are valid. If you try to input something else, you will likely encounter an error at some point. Args: expr (list | str | int | float): a list with a Polish notation expression that describes a, e.g., ["Multiply", ["Sqrt", 2], "x2"] callback (Callable): A function that can return a gurobipy expression associated with the correct model when called with symbol str. Returns: Returns a gurobipy expression (that can belong into one of multiple types) equivalent to the original expressions. All possible output types should be supported as parts of gurobipy constraints. gurobipy.GenExpr at least isn't supported as an objective function. """ if isinstance(expr, gpexpression): # Terminal case: gurobipy expression return expr if isinstance(expr, str): # Terminal case: str expression, represent a variable or expression return callback(expr) if isinstance(expr, self.literals): # Terminal case: numeric literal return expr if isinstance(expr, list): if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self._parse_to_gurobipy(expr[1], callback) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self._parse_to_gurobipy(e, callback) for e in expr[1:]] while isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) if len(expr) == 1 and isinstance(expr[0], str): # Terminal case, single string expression with unnecessary brackets, e.g., ["x1"] instead of "x1" return ( callback(expr[0]) + 0 ) # adding 0 to ensure it's treated as an expression, not a variable reference msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) def _parse_to_cvxpy( self, expr: list | str | int | float, callback: Callable[[str], cvxpyexpression] ) -> cvxpyexpression: """Parses the MathJSON format recursively into a CVXPY expression. CVXPY supports a much broader range of expressions compared to gurobipy, including exponentials, logarithms, and trigonometric functions. However, some operations still have restrictions due to DCP (Disciplined Convex Programming) rules. Args: expr (list | str | int | float): a list with a Polish notation expression that describes a, e.g., ["Multiply", ["Sqrt", 2], "x2"] callback (Callable): A function that can return a CVXPY expression associated with the correct model when called with symbol str. Returns: Returns a CVXPY expression equivalent to the original expression. """ if isinstance(expr, (cp.Variable, cp.Parameter, cp.Expression)): # Terminal case: cvxpy expression return expr if isinstance(expr, str): # Terminal case: str expression, represent a variable or expression return callback(expr) if isinstance(expr, self.literals): # Terminal case: numeric literal return expr if isinstance(expr, list): if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self._parse_to_cvxpy(expr[1], callback) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self._parse_to_cvxpy(e, callback) for e in expr[1:]] while isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) # else, assume the list contents are parseable expressions parsed = [self._parse_to_cvxpy(e, callback) for e in expr] return parsed[0] if len(parsed) == 1 else parsed msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) def _parse_raw_index(self, expr) -> int | tuple[int, ...]: """Convert a MathJSON index spec to a plain Python int or tuple (for Extract/Exclude).""" if isinstance(expr, (int, float)): return int(expr) if isinstance(expr, list) and expr[0] == self.TUPLE: return tuple(int(x) for x in expr[1:]) msg = f"Extract/Exclude index must be an integer or Tuple range, got: {expr!r}" raise ParserError(msg) ``` ##### __init__ ``` __init__(to_format: FormatEnum = 'polars') ``` Create a parser instance for parsing MathJSON notation into polars expressions. Parameters: | Name | Type | Description | Default | | ----------- | ------------ | -------------------------------------------------------------------------------- | ---------- | | `to_format` | `FormatEnum` | to which format a JSON representation should be parsed to. Defaults to "polars". | `'polars'` | Source code in `desdeo/problem/json_parser.py` ``` def __init__(self, to_format: FormatEnum = "polars"): # noqa: C901 """Create a parser instance for parsing MathJSON notation into polars expressions. Args: to_format (FormatEnum, optional): to which format a JSON representation should be parsed to. Defaults to "polars". """ # Define operator names. Change these when the name is altered in the JSON format. # Basic arithmetic operators self.NEGATE: str = "Negate" self.ADD: str = "Add" self.SUB: str = "Subtract" self.MUL: str = "Multiply" self.DIV: str = "Divide" # Vector and matrix operations self.MATMUL: str = "MatMul" self.SUM: str = "Sum" self.RANDOM_ACCESS = "At" self.EXTRACT: str = "Extract" self.EXCLUDE: str = "Exclude" self.TUPLE: str = "Tuple" # Exponentation and logarithms self.EXP: str = "Exp" self.LN: str = "Ln" self.LB: str = "Lb" self.LG: str = "Lg" self.LOP: str = "LogOnePlus" self.SQRT: str = "Sqrt" self.SQUARE: str = "Square" self.POW: str = "Power" # Rounding operators self.ABS: str = "Abs" self.CEIL: str = "Ceil" self.FLOOR: str = "Floor" # Trigonometric operations self.ARCCOS: str = "Arccos" self.ARCCOSH: str = "Arccosh" self.ARCSIN: str = "Arcsin" self.ARCSINH: str = "Arcsinh" self.ARCTAN: str = "Arctan" self.ARCTANH: str = "Arctanh" self.COS: str = "Cos" self.COSH: str = "Cosh" self.SIN: str = "Sin" self.SINH: str = "Sinh" self.TAN: str = "Tan" self.TANH: str = "Tanh" # Comparison operators self.EQUAL: str = "Equal" self.GREATER: str = "Greater" self.GE: str = "GreaterEqual" self.LESS: str = "Less" self.LE: str = "LessEqual" self.NE: str = "NotEqual" # Other operators self.MAX: str = "Max" self.MIN: str = "Min" self.RATIONAL: str = "Rational" self.literals = int | float def _collect_indices(raw_indices: tuple, n: int) -> list[int]: """Collect 0-based indices from a sequence of raw Extract/Exclude specs. Args: raw_indices: the index arguments passed to Extract or Exclude. Each element is either a plain number (single 1-based index) or a tuple ``(start, stop[, step])``. Positive values count from the front; negative values count from the back (e.g. ``-1`` is the last element). n: total length of the array being indexed. Required to resolve negative indices and to clamp out-of-range values. """ def _to_zero(i1: int) -> int: # Convert a 1-based (positive) or end-relative (negative) index to 0-based. return (i1 - 1) if i1 > 0 else (n + i1) indices = [] for spec in raw_indices: if isinstance(spec, tuple): start = _to_zero(int(spec[0])) stop = _to_zero(int(spec[1])) step = int(spec[2]) if len(spec) >= 3 else (1 if stop >= start else -1) # noqa: PLR2004 rng = range(start, stop + 1, step) if step > 0 else range(start, stop - 1, step) indices.extend(i for i in rng if 0 <= i < n) else: zero = _to_zero(int(spec)) if 0 <= zero < n: indices.append(zero) return indices def _extract_from_array(arr, *raw_indices): arr = np.asarray(arr) idx = _collect_indices(raw_indices, arr.shape[0]) return arr[idx].tolist() if idx else [] def _exclude_from_array(arr, *raw_indices): arr = np.asarray(arr) n = arr.shape[0] excluded = set(_collect_indices(raw_indices, n)) keep = [i for i in range(n) if i not in excluded] return arr[keep].tolist() if keep else [] def _polars_extract(expr, *raw_indices): def _fn(acc): arr = acc.to_numpy() if arr.ndim > 1: idx = _collect_indices(raw_indices, arr.shape[-1]) result = arr[..., idx] if idx else np.empty((*arr.shape[:-1], 0), dtype=arr.dtype) else: result = _extract_from_array(arr, *raw_indices) return pl.Series(values=result.tolist()) return to_expr(expr).map_batches(_fn) def _polars_exclude(expr, *raw_indices): def _fn(acc): arr = acc.to_numpy() if arr.ndim > 1: n = arr.shape[-1] excluded = set(_collect_indices(raw_indices, n)) keep = [i for i in range(n) if i not in excluded] result = arr[..., keep] if keep else np.empty((*arr.shape[:-1], 0), dtype=arr.dtype) else: result = _exclude_from_array(arr, *raw_indices) return pl.Series(values=result.tolist()) return to_expr(expr).map_batches(_fn) def _not_impl_extract(*_args): raise NotImplementedError("'Extract' is not implemented for this backend.") def _not_impl_exclude(*_args): raise NotImplementedError("'Exclude' is not implemented for this backend.") def to_expr(x: self.literals | pl.Expr): # type: ignore """Helper function to convert literals to polars expressions.""" return pl.lit(x) if isinstance(x, self.literals) else x def to_sympy_expr(x): return sp.sympify(x, evaluate=False) if isinstance(x, self.literals) else x def gp_error(): msg = "The gurobipy model format only supports linear and quadratic expressions." ParserError(msg) def _polars_pow(base, exponent): base = to_expr(base) exponent = to_expr(exponent) # Detect a constant exponent (the operands have already been parsed to polars # expressions, so a literal arrives as pl.lit(...)). A constant exponent lets us # apply the power via a unary UDF so polars can infer the shape-preserving return # dtype: native `**` does not work on array columns, and an N-ary UDF nested in # other expressions cannot be inferred by polars >=1.31. try: exponent_value = pl.select(exponent).item() except Exception: exponent_value = None if exponent_value is not None: return base.map_batches( lambda series, exp=exponent_value: pl.Series(values=np.power(series.to_numpy(), exp)) ) # Non-constant exponent (rare): native power, which works for scalar operands. return base**exponent def _polars_reduce_unary(expr, ufunc): def _map_function(acc, ufunc=ufunc): # Unary math functions (e.g. log, arctanh) can legitimately hit domain edges such as # log(0) or arctanh(+-1); the resulting inf/nan is the intended evaluation result, so # silence the benign numpy warnings. with np.errstate(divide="ignore", invalid="ignore"): return pl.Series(values=ufunc(acc.to_numpy())) return to_expr(expr).map_batches(_map_function) def _polars_reduce_matmul(*exprs): # Numpy matmul (row-vector dot product OR matrix product) via an N-ary UDF. # No return dtype is declared: polars infers it from a sample, which works # because the surrounding +,-,*,/ are native expressions (not UDFs), so this # UDF is never nested inside another un-inferrable UDF. def _map_function(series_list): acc = series_list[0].to_numpy() for series in series_list[1:]: x = series.to_numpy() if acc.ndim == 2 and x.ndim == 2: # noqa: PLR2004 # row vectors -> per-row dot product (polars has no "column" vectors) acc = np.einsum("ij,ij->i", acc, x, optimize=True) else: acc = np.matmul(acc, x) return pl.Series(values=acc) return pl.map_batches(exprs=[to_expr(expr) for expr in exprs], function=_map_function) def _polars_summation(expr): """Polars matrix summation.""" def _map_function(acc): acc_numpy = acc.to_numpy() return pl.Series(values=np.sum(acc_numpy, axis=tuple(range(1, acc_numpy.ndim)))) return to_expr(expr).map_batches(_map_function) def _polars_random_access(expr, *indices): """Polars tensor random access.""" for index in indices: expr = expr.arr.get(index - 1) # 1 indexing assumed in JSON format return expr def _polars_generic_apply(a, b): pass polars_env = { # Define the operations for the different operators. # Basic arithmetic operations self.NEGATE: lambda x: _polars_reduce_unary(x, np.negative), self.ADD: lambda *args: reduce(lambda a, b: to_expr(a) + to_expr(b), args), self.SUB: lambda *args: reduce(lambda a, b: to_expr(a) - to_expr(b), args), self.MUL: lambda *args: reduce(lambda a, b: to_expr(a) * to_expr(b), args), self.DIV: lambda *args: reduce(lambda a, b: to_expr(a) / to_expr(b), args), # Vector and matrix operations self.MATMUL: _polars_reduce_matmul, self.SUM: lambda x: _polars_summation(x), self.RANDOM_ACCESS: _polars_random_access, self.EXTRACT: _polars_extract, self.EXCLUDE: _polars_exclude, # Exponentiation and logarithms self.EXP: lambda x: _polars_reduce_unary(x, np.exp), self.LN: lambda x: _polars_reduce_unary(x, np.log), self.LB: lambda x: _polars_reduce_unary(x, np.log2), self.LG: lambda x: _polars_reduce_unary(x, np.log10), self.LOP: lambda x: _polars_reduce_unary(x, np.log1p), self.SQRT: lambda x: _polars_reduce_unary(x, np.sqrt), self.SQUARE: lambda x: _polars_reduce_unary(x, lambda y: np.power(y, 2)), self.POW: lambda *args: reduce(_polars_pow, args), # Trigonometric operations self.ARCCOS: lambda x: _polars_reduce_unary(x, np.arccos), self.ARCCOSH: lambda x: _polars_reduce_unary(x, np.arccosh), self.ARCSIN: lambda x: _polars_reduce_unary(x, np.arcsin), self.ARCSINH: lambda x: _polars_reduce_unary(x, np.arcsinh), self.ARCTAN: lambda x: _polars_reduce_unary(x, np.arctan), self.ARCTANH: lambda x: _polars_reduce_unary(x, np.arctanh), self.COS: lambda x: _polars_reduce_unary(x, np.cos), self.COSH: lambda x: _polars_reduce_unary(x, np.cosh), self.SIN: lambda x: _polars_reduce_unary(x, np.sin), self.SINH: lambda x: _polars_reduce_unary(x, np.sinh), self.TAN: lambda x: _polars_reduce_unary(x, np.tan), self.TANH: lambda x: _polars_reduce_unary(x, np.tanh), # Rounding operations self.ABS: lambda x: _polars_reduce_unary(x, np.abs), self.CEIL: lambda x: _polars_reduce_unary(x, np.ceil), self.FLOOR: lambda x: _polars_reduce_unary(x, np.floor), # Other operations self.RATIONAL: lambda lst: reduce(lambda x, y: x / y, lst), # Not supported self.MAX: lambda *args: reduce(lambda x, y: pl.max_horizontal(to_expr(x), to_expr(y)), args), self.MIN: lambda *args: reduce(lambda x, y: pl.min_horizontal(to_expr(x), to_expr(y)), args), } def _pyomo_negate(x): """Negates the given operand.""" def _expr_negate_rule(x): def _inner(_, *indices): return -x[indices] return _inner def _negate(x): # check if operand in indexed if hasattr(x, "index_set") and x.is_indexed(): # indexed, return new pyomo expression expr = pyomo.Expression(x.index_set(), rule=_expr_negate_rule(x)) expr.construct() return expr # not indexed, just regular negate return -x return _negate(x) def _pyomo_pow(base, exp): """Implements a power operator compatible with Pyomo expressions.""" def _expr_pow_rule(base, exp): def _inner(_, *indices): return base[indices] ** exp return _inner def _pow(base, exp=exp): # check if operand in indexed if hasattr(base, "index_set") and base.is_indexed(): # indexed, return new pyomo expression expr = pyomo.Expression(base.index_set(), rule=_expr_pow_rule(base, exp)) expr.construct() return expr # not indexed, just regular power return base**exp return _pow(base, exp) def _pyomo_unary(x, op): """Implements unary operators to work with indexed expressions.""" def _expr_rule(x, op): def _inner(_, *indices, op=op): return op(x[indices]) return _inner def _op(x, op): # check if operand in indexed if hasattr(x, "index_set") and x.is_indexed(): # indexed, return new pyomo expression expr = pyomo.Expression(x.index_set(), rule=_expr_rule(x, op)) expr.construct() return expr # not indexed, just regular power return op(x) return _op(x, op) def _pyomo_addition(*args, subtraction=False): """Add (subtract) scalars or tensors to (from) each other.""" def _expr_matrix_addition_rule(x, y, subtraction=subtraction): def _inner(_, *args): return x[*args] + y[*args] if not subtraction else x[*args] - y[*args] return _inner def _expr_elementwise_with_single_indexed(indexed, not_indexed, subtraction=subtraction): def _inner(_, *indices): return (indexed[indices] + not_indexed) if not subtraction else (indexed[indices] - not_indexed) return _inner def _add(x, y, subtraction=subtraction): # if both are indexed, try matrix addition if (hasattr(x, "index_set") and x.is_indexed()) and (hasattr(y, "index_set") and y.is_indexed()): # try matrix addition # check that the dimensions of x and y matches x_idx, y_idx = x.index_set(), y.index_set() if x_idx.dimen != y_idx.dimen or len(x_idx) != len(y_idx): msg = ( f"The shapes of x ({x_idx.dimen}D, len={len(x_idx)}) and " f"y ({y_idx.dimen}D, len={len(y_idx)}) must match for matrix addition." ) raise ParserError(msg) expr = pyomo.Expression( x.index_set(), rule=_expr_matrix_addition_rule(x, y, subtraction=subtraction) ) expr.construct() return expr # if neither is indexed, do normal addition if not (hasattr(x, "index_set") and x.is_indexed()) and not ( hasattr(y, "index_set") and y.is_indexed() ): if not subtraction: # try regular addition return x + y # try regular subtraction return x - y # x is indexed, y is not if (hasattr(x, "index_set")) and x.is_indexed(): expr = pyomo.Expression( x.index_set(), rule=_expr_elementwise_with_single_indexed(x, y, subtraction=subtraction) ) expr.construct() return expr # if y is indexed, x is not if (hasattr(y, "index_set")) and y.is_indexed(): expr = pyomo.Expression( y.index_set(), rule=_expr_elementwise_with_single_indexed(y, x, subtraction=subtraction) ) expr.construct() return expr # if only one of the operands is indexed, then addition is not supported. Throw error. msg = "For addition, both operands must be either scalars or matrices with matching dimensions." raise ParserError(msg) return reduce(_add, args) def _pyomo_subtraction(*args): return _pyomo_addition(*args, subtraction=True) def _pyomo_multiply(*args, division=False): """Multiply tensor with a scalar.""" def _expr_multiply_with_scalar_rule(scalar_value, to_multiply, division=division): def _inner(_, *indices): return to_multiply[indices] * scalar_value if not division else to_multiply[indices] / scalar_value return _inner def _expr_matrix_multiply_rule(x, y, division=division): def _inner(_, *args): return x[*args] * y[*args] if not division else x[*args] / y[*args] return _inner def _multiply(x, y, division=division): if not hasattr(x, "is_indexed") and not hasattr(y, "is_indexed"): # x and y are scalars return x * y if not division else x / y # check if x or y is scalar if ( hasattr(x, "is_indexed") and x.is_indexed() and x.dim() > 0 and (not hasattr(y, "is_indexed") or not y.is_indexed() or (y.is_indexed() and y.dim() == 0)) ): # x is a tensor, y is scalar expr = pyomo.Expression( x.index_set(), rule=_expr_multiply_with_scalar_rule(y, x, division=division) ) expr.construct() return expr if ( hasattr(y, "is_indexed") and y.is_indexed() and y.dim() > 0 and (not hasattr(x, "is_indexed") or not x.is_indexed() or (x.is_indexed() and x.dim() == 0)) ): # y is a tensor, x is scalar expr = pyomo.Expression( y.index_set(), rule=_expr_multiply_with_scalar_rule(x, y, division=division) ) expr.construct() return expr # check if both are indexed if hasattr(x, "index_set") and hasattr(y, "index_set"): # both are indexed, neither is a scalar, check dims and sized, if match, # multiply together element-wise if x.index_set() != y.index_set(): msg = ( f"The dimensions of x {x.index_set().set_tuple} must match that" f" of y {y.index_set().set_tuple} for element-wise matrix multiplication." ) raise ParserError(msg) expr = pyomo.Expression(x.index_set(), rule=_expr_matrix_multiply_rule(x, y, division=division)) expr.construct() return expr # both are scalars return x * y if not division else x / y return reduce(_multiply, args) def _pyomo_division(*args): return _pyomo_multiply(*args, division=True) def _pyomo_matrix_multiplication(*args): """Multiply two matrices together.""" def _expr_matmul_rule(mat_a, mat_b, j_indices): def _inner(_, i_index, k_index): return sum(mat_a[i_index, j] * mat_b[j, k_index] for j in j_indices) return _inner def _matmul(mat_a, mat_b): if not (hasattr(mat_a, "is_indexed") and mat_a.is_indexed()) or not ( hasattr(mat_b, "is_indexed") and mat_b.is_indexed() ): # either mat_a or mat_b is not tensor msg = "Either mat_a or mat_b, or both, is not indexed. Cannot perform matrix multiplication." raise ParserError(msg) # check for regular vectors, then do dot product if mat_a.dim() == 1 and mat_b.dim() == 1: if (len_a := len(mat_a.index_set())) != (len_b := len(mat_b.index_set())): msg = ( "For dot product, the sizes of the vectors must match." f" Sizes mat_a = {len_a} and mat_b = {len_b}." ) raise ParserError(msg) return pyomo.sum_product(mat_a, mat_b, index=mat_a.index_set()) # assuming mat_a has dimensions i,j; and mat_b j,k; # then the j dimension is squeezed and the i and k dimensions are kept. # check that we are dealing with matrices min_dimension = 2 if ( not hasattr(mat_a.index_set(), "set_tuple") or len(mat_a.index_set().set_tuple) < min_dimension ) or (not hasattr(mat_b.index_set(), "set_tuple") and len(mat_b.index_set().set_tuple) < min_dimension): msg = "Both mat_a and mat_b must have at least two dimensions." raise ParserError(msg) # check that the outer dimensions (the one to be squeezed) matches if len(mat_a.index_set().set_tuple[-1]) != len(mat_b.index_set().set_tuple[0]): msg = ( f"The last dimension size of mat_a ({mat_a.index_set().set_tuple[-1]}) must " f"match the first dimension of mat_b ({mat_b.index_set().set_tuple[0]})" ) raise ParserError(msg) expr = pyomo.Expression( mat_a.index_set().set_tuple[0], mat_b.index_set().set_tuple[1], rule=_expr_matmul_rule(mat_a, mat_b, mat_a.index_set().set_tuple[1]), ) expr.construct() return expr return reduce(_matmul, args) def _pyomo_summation(summand): """Sum an indexed Pyomo object.""" return pyomo.sum_product(summand, index=summand.index_set()) def _pyomo_random_access(indexed, *indices): return indexed[*indices] def _pyomo_extract(indexed, *raw_indices): if not (hasattr(indexed, "index_set") and indexed.is_indexed()): msg = "'Extract' requires an indexed Pyomo expression." raise ParserError(msg) all_indices = sorted(indexed.index_set()) n = len(all_indices) positions = _collect_indices(raw_indices, n) selected = [all_indices[p] for p in positions] new_set = pyomo.RangeSet(1, len(selected)) idx_map = {i + 1: sel for i, sel in enumerate(selected)} expr = pyomo.Expression(new_set, rule=lambda _, i: indexed[idx_map[i]]) expr.construct() return expr def _pyomo_exclude(indexed, *raw_indices): if not (hasattr(indexed, "index_set") and indexed.is_indexed()): msg = "'Exclude' requires an indexed Pyomo expression." raise ParserError(msg) all_indices = sorted(indexed.index_set()) n = len(all_indices) excluded_pos = set(_collect_indices(raw_indices, n)) keep = [all_indices[p] for p in range(n) if p not in excluded_pos] new_set = pyomo.RangeSet(1, len(keep)) idx_map = {i + 1: k for i, k in enumerate(keep)} expr = pyomo.Expression(new_set, rule=lambda _, i: indexed[idx_map[i]]) expr.construct() return expr pyomo_env = { # Define the operations for the different operators. # Basic arithmetic operations self.NEGATE: _pyomo_negate, self.ADD: _pyomo_addition, self.SUB: _pyomo_subtraction, self.MUL: _pyomo_multiply, self.DIV: _pyomo_division, # Vector and matrix operations self.MATMUL: _pyomo_matrix_multiplication, self.SUM: _pyomo_summation, self.RANDOM_ACCESS: _pyomo_random_access, self.EXTRACT: _pyomo_extract, self.EXCLUDE: _pyomo_exclude, # Exponentiation and logarithms self.EXP: lambda x: _pyomo_unary(x, pyomo.exp), self.LN: lambda x: _pyomo_unary(x, pyomo.log), self.LB: lambda x: _pyomo_unary( x, lambda x: pyomo.log(x) / pyomo.log(2) ), # change of base, pyomo has no log2 self.LG: lambda x: _pyomo_unary(x, pyomo.log10), self.LOP: lambda x: _pyomo_unary(x, lambda x: pyomo.log(x + 1)), self.SQRT: lambda x: _pyomo_unary(x, pyomo.sqrt), self.SQUARE: lambda x: _pyomo_pow(x, 2), self.POW: lambda x, y: _pyomo_pow(x, y), # Trigonometric operations self.ARCCOS: lambda x: _pyomo_unary(x, pyomo.acos), self.ARCCOSH: lambda x: _pyomo_unary(x, pyomo.acosh), self.ARCSIN: lambda x: _pyomo_unary(x, pyomo.asin), self.ARCSINH: lambda x: _pyomo_unary(x, pyomo.asinh), self.ARCTAN: lambda x: _pyomo_unary(x, pyomo.atan), self.ARCTANH: lambda x: _pyomo_unary(x, pyomo.atanh), self.COS: lambda x: _pyomo_unary(x, pyomo.cos), self.COSH: lambda x: _pyomo_unary(x, pyomo.cosh), self.SIN: lambda x: _pyomo_unary(x, pyomo.sin), self.SINH: lambda x: _pyomo_unary(x, pyomo.sinh), self.TAN: lambda x: _pyomo_unary(x, pyomo.tan), self.TANH: lambda x: _pyomo_unary(x, pyomo.tanh), # Rounding operations self.ABS: lambda x: _pyomo_unary(x, abs), self.CEIL: lambda x: _pyomo_unary(x, pyomo.ceil), self.FLOOR: lambda x: _pyomo_unary(x, pyomo.floor), # Other operations self.RATIONAL: lambda lst: reduce(lambda x, y: x / y, lst), # not supported # probably a better idea to reformulate expressions with a max when utilized with pyomo # self.MAX: lambda *args: reduce(lambda x, y: _PyomoMax((x, y)), args), self.MAX: lambda *args: _PyomoMax(args), self.MIN: lambda *args: _PyomoMin(args), } def _sympy_matmul(*args): """Sympy matrix multiplication.""" msg = ( "Matrix multiplication '@' has not been implemented for the Sympy parser yet. Feel free to contribute!" ) raise NotImplementedError(msg) def _sympy_summation(summand): """Sympy matrix summation.""" msg = "Matrix summation 'Sum' has not been implemented for the Sympy parser yet. Feel free to contribute!" raise NotImplementedError(msg) def _sympy_random_access(*args): msg = ( "Tensor random access with 'At' has not been implemented for the Sympy parser yet. " "Feel free to contribute!" ) raise NotImplementedError(msg) sympy_env = { # Basic arithmetic operations self.NEGATE: lambda x: -to_sympy_expr(x), self.ADD: lambda *args: reduce(lambda x, y: to_sympy_expr(x) + to_sympy_expr(y), args), self.SUB: lambda *args: reduce(lambda x, y: to_sympy_expr(x) - to_sympy_expr(y), args), self.MUL: lambda *args: reduce(lambda x, y: to_sympy_expr(x) * to_sympy_expr(y), args), self.DIV: lambda *args: reduce(lambda x, y: to_sympy_expr(x) / to_sympy_expr(y), args), # Vector and matrix operations self.MATMUL: _sympy_matmul, self.SUM: _sympy_summation, self.RANDOM_ACCESS: _sympy_random_access, self.EXTRACT: _not_impl_extract, self.EXCLUDE: _not_impl_exclude, # Exponentiation and logarithms self.EXP: lambda x: sp.exp(to_sympy_expr(x)), self.LN: lambda x: sp.log(to_sympy_expr(x)), self.LB: lambda x: sp.log(to_sympy_expr(x), 2), self.LG: lambda x: sp.log(to_sympy_expr(x), 10), self.LOP: lambda x: sp.log(1 + to_sympy_expr(x)), self.SQRT: lambda x: sp.sqrt(to_sympy_expr(x)), self.SQUARE: lambda x: to_sympy_expr(x) ** 2, self.POW: lambda x, y: to_sympy_expr(x) ** to_sympy_expr(y), # Trigonometric operations self.SIN: lambda x: sp.sin(to_sympy_expr(x)), self.COS: lambda x: sp.cos(to_sympy_expr(x)), self.TAN: lambda x: sp.tan(to_sympy_expr(x)), self.ARCSIN: lambda x: sp.asin(to_sympy_expr(x)), self.ARCCOS: lambda x: sp.acos(to_sympy_expr(x)), self.ARCTAN: lambda x: sp.atan(to_sympy_expr(x)), # Hyperbolic functions self.SINH: lambda x: sp.sinh(to_sympy_expr(x)), self.COSH: lambda x: sp.cosh(to_sympy_expr(x)), self.TANH: lambda x: sp.tanh(to_sympy_expr(x)), self.ARCSINH: lambda x: sp.asinh(to_sympy_expr(x)), self.ARCCOSH: lambda x: sp.acosh(to_sympy_expr(x)), self.ARCTANH: lambda x: sp.atanh(to_sympy_expr(x)), # Other self.ABS: lambda x: sp.Abs(to_sympy_expr(x)), self.CEIL: lambda x: sp.ceiling(to_sympy_expr(x)), self.FLOOR: lambda x: sp.floor(to_sympy_expr(x)), # Note: Max and Min in sympy take any number of arguments self.MAX: lambda *args: sp.Max(*args), self.MIN: lambda *args: sp.Min(*args), # Rational numbers, for now assuming two-element list for numerator and denominator self.RATIONAL: lambda x, y: sp.Rational(x, y), } def _gurobipy_multiply(*args): """Multiply, promoting scalar gp.Var * ndarray to MLinExpr via MVar.fromlist.""" def _mul(a, b): if isinstance(a, gp.Var) and isinstance(b, np.ndarray): return gp.MVar.fromlist([a]) * b if isinstance(b, gp.Var) and isinstance(a, np.ndarray): return gp.MVar.fromlist([b]) * a return a * b return reduce(_mul, args) def _gurobipy_matmul(*args): """Gurobipy matrix multiplication.""" def _matmul(a, b): if isinstance(a, list): a = np.array(a) if isinstance(b, list): b = np.array(b) return a @ b return reduce(_matmul, args) def _gurobipy_summation(summand): """Gurobipy matrix summation.""" def _sum(summand): if isinstance(summand, list): summand = np.array(summand) return summand.sum() return _sum(summand) def _gurobipy_random_access(indexed, *indices): # 1-based indexing assumed in JSON format; convert to 0-based for Python/numpy/gp.MVar zero_based = tuple(int(i) - 1 for i in indices) if len(zero_based) == 1: return indexed[zero_based[0]] return indexed[zero_based] def _gurobipy_extract(arr, *raw_indices): idx = _collect_indices(raw_indices, arr.shape[0]) return arr[idx] def _gurobipy_exclude(arr, *raw_indices): n = arr.shape[0] excluded = set(_collect_indices(raw_indices, n)) keep = [i for i in range(n) if i not in excluded] return arr[keep] gurobipy_env = { # Define the operations for the different operators. # Basic arithmetic operations self.NEGATE: lambda x: -x, self.ADD: lambda *args: reduce(lambda x, y: x + y, args), self.SUB: lambda *args: reduce(lambda x, y: x - y, args), self.MUL: _gurobipy_multiply, self.DIV: lambda *args: reduce(lambda x, y: x / y, args), # Vector and matrix operations self.MATMUL: _gurobipy_matmul, self.SUM: _gurobipy_summation, self.RANDOM_ACCESS: _gurobipy_random_access, self.EXTRACT: _gurobipy_extract, self.EXCLUDE: _gurobipy_exclude, # Exponentiation and logarithms # it would be possible to implement some of these with the special functions that # gurobi has to offer, but they would only work under specific circumstances self.EXP: lambda x: gp_error(), self.LN: lambda x: gp_error(), self.LB: lambda x: gp_error(), self.LG: lambda x: gp_error(), self.LOP: lambda x: gp_error(), self.SQRT: lambda x: gp_error(), self.SQUARE: lambda x: x**2, self.POW: lambda x, y: x**y, # this will likely cause an error at some point for most y # Trigonometric operations # it would be possible to implement some of these with the special functions that # gurobi has to offer, but they would only work under specific circumstances self.ARCCOS: lambda x: gp_error(), self.ARCCOSH: lambda x: gp_error(), self.ARCSIN: lambda x: gp_error(), self.ARCSINH: lambda x: gp_error(), self.ARCTAN: lambda x: gp_error(), self.ARCTANH: lambda x: gp_error(), self.COS: lambda x: gp_error(), self.COSH: lambda x: gp_error(), self.SIN: lambda x: gp_error(), self.SINH: lambda x: gp_error(), self.TAN: lambda x: gp_error(), self.TANH: lambda x: gp_error(), # Rounding operations self.ABS: lambda x: gp.abs_(x), self.CEIL: lambda x: gp_error(), self.FLOOR: lambda x: gp_error(), # Other operations self.RATIONAL: lambda lst: reduce(lambda x, y: x / y, lst), # not supported self.MAX: lambda *args: gp.max_(args), ## OBS! max and min are unsupported, but left here for reasons self.MIN: lambda *args: gp.min_(args), } def _cvxpy_error(): msg = "The cvxpy model format only supports linear and quadratic expressions." return lambda x: (_ for _ in ()).throw(ParserError(msg)) def _cvxpy_matmul(*args): """CVXPY matrix multiplication.""" def _matmul(a, b): if isinstance(a, list): a = np.array(a) if isinstance(b, list): b = np.array(b) return a @ b return reduce(_matmul, args) def _cvxpy_summation(summand): """CVXPY matrix summation.""" def _sum(summand): if isinstance(summand, list): summand = np.array(summand) return cp.sum(summand) return _sum(summand) def _cvxpy_random_access(indexed, *indices): zero_based = tuple(int(i) - 1 for i in indices) if len(zero_based) == 1: return indexed[zero_based[0]] return indexed[zero_based] def _cvxpy_extract(expr, *raw_indices): n = expr.shape[0] idx = _collect_indices(raw_indices, n) return expr[idx] def _cvxpy_exclude(expr, *raw_indices): n = expr.shape[0] excluded = set(_collect_indices(raw_indices, n)) keep = [i for i in range(n) if i not in excluded] return expr[keep] cvxpy_env = { # Define the operations for the different operators. # Basic arithmetic operations self.NEGATE: lambda x: -x, self.ADD: lambda *args: reduce(lambda x, y: x + y, args), self.SUB: lambda *args: reduce(lambda x, y: x - y, args), self.MUL: lambda *args: reduce(lambda x, y: x * y, args), self.DIV: lambda *args: reduce(lambda x, y: x / y, args), # Vector and matrix operations self.MATMUL: _cvxpy_matmul, self.SUM: _cvxpy_summation, self.RANDOM_ACCESS: _cvxpy_random_access, self.EXTRACT: _cvxpy_extract, self.EXCLUDE: _cvxpy_exclude, # Exponentiation and logarithms # CVXPY supports some of these via special functions, but with restrictions self.EXP: lambda x: cp.exp(x), self.LN: lambda x: cp.log(x), self.LB: lambda x: cp.log(x) / np.log(2), self.LG: lambda x: cp.log(x) / np.log(10), self.LOP: lambda x: cp.log1p(x), self.SQRT: lambda x: cp.sqrt(x), self.SQUARE: lambda x: cp.square(x), self.POW: lambda x, y: x**y, # may cause errors for non-integer powers # Trigonometric operations - CVXPY supports these self.ARCCOS: lambda x: cp.arccos(x), self.ARCCOSH: lambda x: cp.arccosh(x), self.ARCSIN: lambda x: cp.arcsin(x), self.ARCSINH: lambda x: cp.arcsinh(x), self.ARCTAN: lambda x: cp.arctan(x), self.ARCTANH: lambda x: cp.arctanh(x), self.COS: lambda x: cp.cos(x), self.COSH: lambda x: cp.cosh(x), self.SIN: lambda x: cp.sin(x), self.SINH: lambda x: cp.sinh(x), self.TAN: lambda x: cp.tan(x), self.TANH: lambda x: cp.tanh(x), # Rounding operations self.ABS: lambda x: cp.abs(x), self.CEIL: lambda x: cp.ceil(x), self.FLOOR: lambda x: cp.floor(x), # Other operations self.RATIONAL: lambda lst: reduce(lambda x, y: x / y, lst), self.MAX: lambda *args: cp.max(cp.stack(args, axis=0), axis=0), self.MIN: lambda *args: cp.min(cp.stack(args, axis=0), axis=0), } match to_format: case FormatEnum.polars: self.env = polars_env self.parse = self._parse_to_polars case FormatEnum.pyomo: self.env = pyomo_env self.parse = self._parse_to_pyomo case FormatEnum.sympy: self.env = sympy_env self.parse = self._parse_to_sympy case FormatEnum.gurobipy: self.env = gurobipy_env self.parse = self._parse_to_gurobipy case FormatEnum.cvxpy: self.env = cvxpy_env self.parse = self._parse_to_cvxpy case _: msg = f"Given target format {to_format} not supported. Must be one of {FormatEnum}." raise ParserError(msg) ``` ##### \_parse_raw_index ``` _parse_raw_index(expr) -> int | tuple[int, ...] ``` Convert a MathJSON index spec to a plain Python int or tuple (for Extract/Exclude). Source code in `desdeo/problem/json_parser.py` ``` def _parse_raw_index(self, expr) -> int | tuple[int, ...]: """Convert a MathJSON index spec to a plain Python int or tuple (for Extract/Exclude).""" if isinstance(expr, (int, float)): return int(expr) if isinstance(expr, list) and expr[0] == self.TUPLE: return tuple(int(x) for x in expr[1:]) msg = f"Extract/Exclude index must be an integer or Tuple range, got: {expr!r}" raise ParserError(msg) ``` ##### \_parse_to_cvxpy ``` _parse_to_cvxpy( expr: list | str | int | float, callback: Callable[[str], cvxpyexpression], ) -> cvxpyexpression ``` Parses the MathJSON format recursively into a CVXPY expression. CVXPY supports a much broader range of expressions compared to gurobipy, including exponentials, logarithms, and trigonometric functions. However, some operations still have restrictions due to DCP (Disciplined Convex Programming) rules. Parameters: | Name | Type | Description | Default | | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------ | ---------- | | `expr` | \`list | str | int | | `callback` | `Callable` | A function that can return a CVXPY expression associated with the correct model when called with symbol str. | *required* | Returns: | Type | Description | | ----------------- | ----------------------------------------------------------------- | | `cvxpyexpression` | Returns a CVXPY expression equivalent to the original expression. | Source code in `desdeo/problem/json_parser.py` ``` def _parse_to_cvxpy( self, expr: list | str | int | float, callback: Callable[[str], cvxpyexpression] ) -> cvxpyexpression: """Parses the MathJSON format recursively into a CVXPY expression. CVXPY supports a much broader range of expressions compared to gurobipy, including exponentials, logarithms, and trigonometric functions. However, some operations still have restrictions due to DCP (Disciplined Convex Programming) rules. Args: expr (list | str | int | float): a list with a Polish notation expression that describes a, e.g., ["Multiply", ["Sqrt", 2], "x2"] callback (Callable): A function that can return a CVXPY expression associated with the correct model when called with symbol str. Returns: Returns a CVXPY expression equivalent to the original expression. """ if isinstance(expr, (cp.Variable, cp.Parameter, cp.Expression)): # Terminal case: cvxpy expression return expr if isinstance(expr, str): # Terminal case: str expression, represent a variable or expression return callback(expr) if isinstance(expr, self.literals): # Terminal case: numeric literal return expr if isinstance(expr, list): if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self._parse_to_cvxpy(expr[1], callback) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self._parse_to_cvxpy(e, callback) for e in expr[1:]] while isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) # else, assume the list contents are parseable expressions parsed = [self._parse_to_cvxpy(e, callback) for e in expr] return parsed[0] if len(parsed) == 1 else parsed msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) ``` ##### \_parse_to_gurobipy ``` _parse_to_gurobipy( expr: list | str | int | float, callback: Callable[[str], gpexpression | int | float], ) -> gpexpression | int | float ``` Parses the MathJSON format recursively into a gurobipy expression. Gurobi only fundamentally supports linear and quadratic expressions, and this parser does not check that the inputs are valid. If you try to input something else, you will likely encounter an error at some point. Parameters: | Name | Type | Description | Default | | ---------- | ---------- | --------------------------------------------------------------------------------------------------------------- | ---------- | | `expr` | \`list | str | int | | `callback` | `Callable` | A function that can return a gurobipy expression associated with the correct model when called with symbol str. | *required* | Returns: | Type | Description | | -------------- | ----------- | | \`gpexpression | int | | \`gpexpression | int | | \`gpexpression | int | | \`gpexpression | int | Source code in `desdeo/problem/json_parser.py` ``` def _parse_to_gurobipy( self, expr: list | str | int | float, callback: Callable[[str], gpexpression | int | float] ) -> gpexpression | int | float: """Parses the MathJSON format recursively into a gurobipy expression. Gurobi only fundamentally supports linear and quadratic expressions, and this parser does not check that the inputs are valid. If you try to input something else, you will likely encounter an error at some point. Args: expr (list | str | int | float): a list with a Polish notation expression that describes a, e.g., ["Multiply", ["Sqrt", 2], "x2"] callback (Callable): A function that can return a gurobipy expression associated with the correct model when called with symbol str. Returns: Returns a gurobipy expression (that can belong into one of multiple types) equivalent to the original expressions. All possible output types should be supported as parts of gurobipy constraints. gurobipy.GenExpr at least isn't supported as an objective function. """ if isinstance(expr, gpexpression): # Terminal case: gurobipy expression return expr if isinstance(expr, str): # Terminal case: str expression, represent a variable or expression return callback(expr) if isinstance(expr, self.literals): # Terminal case: numeric literal return expr if isinstance(expr, list): if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self._parse_to_gurobipy(expr[1], callback) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self._parse_to_gurobipy(e, callback) for e in expr[1:]] while isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) if len(expr) == 1 and isinstance(expr[0], str): # Terminal case, single string expression with unnecessary brackets, e.g., ["x1"] instead of "x1" return ( callback(expr[0]) + 0 ) # adding 0 to ensure it's treated as an expression, not a variable reference msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) ``` ##### \_parse_to_polars ``` _parse_to_polars(expr: list | str | int | float) -> pl.Expr ``` Recursively parses JSON math expressions and returns a polars expression. Parameters: | Name | Type | Description | Default | | ------ | ------ | -------------------------------------------------------------------------------------------------- | ---------- | | `expr` | `list` | A list with a Polish notation expression that describes a, e.g., \["Multiply", ["Sqrt", 2], "x2"\] | *required* | Raises: | Type | Description | | ------------- | ------------------------------------------------ | | `ParserError` | when a unsupported operator type is encountered. | Returns: | Type | Description | | ------ | ----------------------------------------------------------- | | `Expr` | pl.Expr: A polars expression that may be evaluated further. | Source code in `desdeo/problem/json_parser.py` ``` def _parse_to_polars(self, expr: list | str | int | float) -> pl.Expr: """Recursively parses JSON math expressions and returns a polars expression. Arguments: expr (list): A list with a Polish notation expression that describes a, e.g., ["Multiply", ["Sqrt", 2], "x2"] Raises: ParserError: when a unsupported operator type is encountered. Returns: pl.Expr: A polars expression that may be evaluated further. """ if isinstance(expr, pl.Expr): # Terminal case: polars expression return expr if isinstance(expr, str): # Terminal case: str expression (represents a column name) return pl.col(expr) if isinstance(expr, self.literals): # Terminal case: numeric literal return pl.lit(expr) if isinstance(expr, list): if len(expr) == 1 and isinstance(expr[0], str | self.literals): # Terminal case, single symbol expression or literal if isinstance(expr[0], str): return pl.col(expr) # just a literal return pl.lit(expr[0]) # Extract/Exclude: index args must stay as raw Python values, not polars expressions. if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self.parse(expr[1]) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self.parse(e) for e in expr[1:]] if isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) # else, assume the list contents are parseable expressions return [self.parse(e) for e in expr] msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) ``` ##### \_parse_to_pyomo ``` _parse_to_pyomo( expr: list | str | int | float | Expression, model: Model, ) -> pyomo.Expression ``` Parses the MathJSON format recursively into a Pyomo expression. Parameters: | Name | Type | Description | Default | | ------- | ------- | ----------------------------------------------------------------------------------------------------------- | ---------- | | `expr` | \`list | str | int | | `model` | `Model` | a pyomo model with the symbols defined appearing in the expression. E.g., "x2" -> model.x2 must be defined. | *required* | Raises: | Type | Description | | ------------- | ------------------------------------------------ | | `ParserError` | when a unsupported operator type is encountered. | Returns: | Type | Description | | ------------ | ------------------------------------------------------------------------------------ | | `Expression` | pyomo.Expression: returns a pyomo expression equivalent to the original expressions. | Source code in `desdeo/problem/json_parser.py` ``` def _parse_to_pyomo( self, expr: list | str | int | float | pyomo.Expression, model: pyomo.Model ) -> pyomo.Expression: """Parses the MathJSON format recursively into a Pyomo expression. Args: expr (list | str | int | float): a list with a Polish notation expression that describes a, e.g., ["Multiply", ["Sqrt", 2], "x2"] model (pyomo.Model): a pyomo model with the symbols defined appearing in the expression. E.g., "x2" -> model.x2 must be defined. Raises: ParserError: when a unsupported operator type is encountered. Returns: pyomo.Expression: returns a pyomo expression equivalent to the original expressions. """ if isinstance(expr, pyomo.Expression): # Terminal case: pyomo expression return expr if isinstance(expr, str): # Terminal case: str expression, represent a variable or expression return getattr(model, expr) if isinstance(expr, self.literals): # Terminal case: numeric literal return expr if isinstance(expr, list): if len(expr) == 1 and isinstance(expr[0], str | self.literals): # Terminal case, single symbol expression or literal if isinstance(expr[0], str): return getattr(model, expr[0]) # just a literal return pyomo.Expression(expr=expr[0]) if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self._parse_to_pyomo(expr[1], model) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self._parse_to_pyomo(e, model) for e in expr[1:]] if isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) # else, assume the list contents are parseable expressions return [self._parse_to_pyomo(e, model) for e in expr] msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) ``` ##### \_parse_to_sympy ``` _parse_to_sympy( expr: list | str | int | float | Basic, ) -> sp.Basic ``` Parse the MathJSON format recursively into a sympy expression. Parameters: | Name | Type | Description | Default | | ------ | ------ | ----------- | ------- | | `expr` | \`list | str | int | Raises: | Type | Description | | ------------- | ------------------------------------------------ | | `ParserError` | when a unsupported operator type is encountered. | Returns: | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------ | | `Basic` | sp.Basic: a sympy expression that represents the original mathematical expression in the supplied MathJSON format. | Source code in `desdeo/problem/json_parser.py` ``` def _parse_to_sympy(self, expr: list | str | int | float | sp.Basic) -> sp.Basic: """Parse the MathJSON format recursively into a sympy expression. Args: expr (list | str | int | float | sp.Basic): base call should be a list in Polish notation representing a mathematical expression. Recursion calls can be of various types. Raises: ParserError: when a unsupported operator type is encountered. Returns: sp.Basic: a sympy expression that represents the original mathematical expression in the supplied MathJSON format. """ if isinstance(expr, sp.Basic): # Terminal case: sympy expression return expr if isinstance(expr, str): # Terminal case: represents a variable return sp.sympify(expr, evaluate=False) if isinstance(expr, self.literals): # Terminal case: numeric literal return sp.sympify(expr, evaluate=False) if isinstance(expr, list): if len(expr) == 1 and isinstance(expr[0], str | self.literals): # Terminal case, single symbol expression or literal return sp.sympify(expr[0], evaluate=False) if expr[0] in (self.EXTRACT, self.EXCLUDE): collection = self.parse(expr[1]) raw_indices = [self._parse_raw_index(e) for e in expr[2:]] return self.env[expr[0]](collection, *raw_indices) # Extract the operation name if isinstance(expr[0], str) and expr[0] in self.env: op_name = expr[0] # Parse the operands operands = [self.parse(e) for e in expr[1:]] if isinstance(operands, list) and len(operands) == 1: # if the operands have redundant brackets, remove them operands = operands[0] if isinstance(operands, list): return self.env[op_name](*operands) return self.env[op_name](operands) # else, assume the list contents are parseable expressions return [self.parse(e) for e in expr] msg = f"Encountered unsupported type '{type(expr)}' during parsing." raise ParserError(msg) ``` #### ParserError Bases: `Exception` Raised when an error related to the MathParser class in encountered. Source code in `desdeo/problem/json_parser.py` ``` class ParserError(Exception): """Raised when an error related to the MathParser class in encountered.""" ``` #### replace_str ``` replace_str( lst: list | str, target: str, sub: list | str | float | int, ) -> list ``` Replace a target in list with a substitution recursively. Parameters: | Name | Type | Description | Default | | -------- | ------------- | ---------------------------------------------- | ---------- | | `lst` | `list or str` | The list where the substitution is to be made. | *required* | | `target` | `str` | The target of the substitution. | *required* | | `sub` | `list or str` | The content to substitute the target. | *required* | Return list or str: The list or str with the substitution. Example replace_str("\["Max", "g_i", ["Add","g_i","f_i"]\]\]", "\_i", "\_1") ---> \["Max", "g_1", ["Add","g_1","f_1"]\]\] Source code in `desdeo/problem/json_parser.py` ``` def replace_str(lst: list | str, target: str, sub: list | str | float | int) -> list: """Replace a target in list with a substitution recursively. Arguments: lst (list or str): The list where the substitution is to be made. target (str): The target of the substitution. sub (list or str): The content to substitute the target. Return: list or str: The list or str with the substitution. Example: replace_str("["Max", "g_i", ["Add","g_i","f_i"]]]", "_i", "_1") ---> ["Max", "g_1", ["Add","g_1","f_1"]]] """ if isinstance(lst, list): return [replace_str(item, target, sub) for item in lst] if isinstance(lst, str): if target == lst: if isinstance(sub, str): return lst.replace(target, sub) return sub return lst return lst ``` ## Infix parser ### desdeo.problem.infix_parser Defines parsers for parsing mathematical expression in an infix format and expressed as string. Currently, mostly parses to MathJSON, e.g., "n / (1 + n)" -> \['Divide', 'n', ['Add', 1, 'n']\]. #### InfixExpressionParser A class for defining infix notation parsers. Source code in `desdeo/problem/infix_parser.py` ``` class InfixExpressionParser: """A class for defining infix notation parsers.""" SUPPORTED_TARGETS: ClassVar[list] = ["MathJSON"] # Supported infix binary operators, i.e., '1+1'. The key is the notation of the operator in infix format, # and the value the notation in parsed format. BINARY_OPERATORS: ClassVar[dict] = { "+": "Add", "-": "Subtract", "*": "Multiply", "/": "Divide", "**": "Power", "@": "MatMul", } # Supported infix unary operators, i.e., 'Cos(90)'. The key is the notation of the operator in infix format, # and the value the notation in parsed format. UNARY_OPERATORS: ClassVar[dict] = { "Cos": "Cos", "Sin": "Sin", "Tan": "Tan", "Exp": "Exp", "Ln": "Ln", "Lb": "Lb", "Lg": "Lg", "LogOnePlus": "LogOnePlus", "Sqrt": "Sqrt", "Square": "Square", "Abs": "Abs", "Ceil": "Ceil", "Floor": "Floor", "Arccos": "Arccos", "Arccosh": "Arccosh", "Arcsin": "Arcsin", "Arcsinh": "Arcsinh", "Arctan": "Arctan", "Arctanh": "Arctanh", "Cosh": "Cosh", "Sinh": "Sinh", "Tanh": "Tanh", "Rational": "Rational", "-": "Negate", "Sum": "Sum", } # Supported infix variadic operators (operators that take one or more comma separated arguments), # i.e., 'Max(1,2, Cos(3)). The key is the notation of the operator in infix format, # and the value the notation in parsed format. VARIADIC_OPERATORS: ClassVar[dict] = {"Max": "Max", "Min": "Min"} def __init__(self, target="MathJSON"): """A parser for infix notation, e.g., the huma readable way of notating mathematical expressions. The parser can parse infix notation stored in a string to different formats. For instance, "Cos(2 + f_1) - 7.2 + Max(f_2, -f_3)" is first parsed to the list: ['Cos', [[2, '+', 'f_1']]], '-', 7.2, '+', ['Max', ['f_2', ['-', 'f_3']]. Then, if parsed to the MathJSON format, it will be parsed to the list: [ [["Subtract", ["Cos", ["Add", 2, "f_1"]], ["Add", 7.2, ["Max", ["f_2", ["Negate", "f_3"]]]]]] ]. Args: target (str, optional): The target format to parse an infix expression to. Currently only "MathJSON" is supported. Defaults to "MathJSON". """ if target not in InfixExpressionParser.SUPPORTED_TARGETS: msg = f"The target '{target} is not supported. Should be one of {InfixExpressionParser.SUPPORTED_TARGETS}" raise ValueError(msg) self.target = target # Scope limiters lparen = Suppress("(") rparen = Suppress(")") lbracket = Suppress("[") rbracket = Suppress("]") # Define keywords (Note that binary operators must be defined manually) symbols_variadic = set(InfixExpressionParser.VARIADIC_OPERATORS) symbols_unary = set(InfixExpressionParser.UNARY_OPERATORS) # Define binary operation symbols (this is the manual part) # If new binary operators are to be added, they must be defined here. signop = one_of("+ -") multop = one_of("* / . @") plusop = one_of("+ -") expop = Literal("**") # Dynamically create Keyword objects for variadric functions variadic_pattern = r"\b(" + f"{'|'.join([*symbols_variadic])}" + r")\b" variadic_func_names = Regex(variadic_pattern) # Dynamically create Keyword objects for unary functions # unary_func_names = reduce(or_, (Keyword(k) for k in symbols_unary)) unary_pattern = r"\b(" + f"{'|'.join([*symbols_unary])}" + r")\b" unary_func_names = Regex(unary_pattern) # Define operands integer = pyparsing_common.integer # Scientific notation scientific = pyparsing_common.sci_real # Complete regex pattern with exclusions and identifier pattern exclude = f"{'|'.join([*symbols_variadic, *symbols_unary])}" pattern = r"(?!\b(" + exclude + r")\b)(\b[a-zA-Z_][a-zA-Z0-9_]*\b)" variable = Regex(pattern)("variable") # Forward declarations of variadic, unary, and bracket function calls variadic_call = Forward() unary_call = Forward() bracket_access = Forward() operands = variable | scientific | integer # Define bracket access. Brackets following a variable may contain only integer values. index_list = Group(DelimitedList(integer))("bracket_indices") bracket_access <<= Group(variable + lbracket + index_list + rbracket) # The parsed expressions are assumed to follow a standard infix syntax. The operands # of the infix syntax can be either the literal 'operands' defined above (these are singletons), # or either a variadic function call or a unary function call. These latter two will be # defined to be recursive. # # Note that the order of the operators in the second argument (the list) of infixNotation matters! # The operation with the highest precedence is listed first. infix_expn = infix_notation( bracket_access | operands | variadic_call | unary_call, [ (expop, 2, OpAssoc.LEFT), (signop, 1, OpAssoc.RIGHT), (multop, 2, OpAssoc.LEFT), (plusop, 2, OpAssoc.LEFT), ], )("binary_operator") # These are recursive definitions of the forward declarations of the two type of function calls. # In essence, the recursion continues until a singleton operand is encountered. variadic_call <<= Group(variadic_func_names + lparen + Group(DelimitedList(infix_expn)) + rparen)( "variadic_call" ) unary_call <<= Group(unary_func_names + lparen + Group(infix_expn) + rparen)("unary_call") self.expn = infix_expn # The infix operations do not need to be in this list because they are handled by infixNotation() above. # If new binary operations are to be added, they must be updated in the infixNotation() call (the list). self.reserved_symbols: set[str] = symbols_unary | symbols_variadic # It is assumed that the dicts in the three class variables have unique keys. self.operator_mapping = { **InfixExpressionParser.BINARY_OPERATORS, **InfixExpressionParser.UNARY_OPERATORS, **InfixExpressionParser.VARIADIC_OPERATORS, } if self.target == "MathJSON": self.pre_parse = self._pre_parse self.parse_to_target = self._to_math_json else: self.pre_parse = None self.parse_to_target = None def _pre_parse(self, str_expr: str): return self.expn.parse_string(str_expr, parse_all=True) def _is_number_or_variable(self, c): return isinstance(c, int | float) or (isinstance(c, str) and c not in self.reserved_symbols) def _to_math_json(self, parsed: list | str) -> list: """Converts a list of expressions into a MathJSON compliant format. The conversion happens recursively. Each list of recursed until a terminal character is reached. Terminal characters are integers (int), floating point numbers (float), or non-keyword strings (str). Keyword strings are reserved for operations, such as 'Cos' or 'Max'. Args: parsed (list): A list possibly containing other lists. Represents a mathematical expression. Returns: list: A list representing a mathematical expression in a MathJSON compliant format. """ # Directly return the input if it is an integer or a float if self._is_number_or_variable(parsed): return parsed # Handle bracket access # Assume that anything following variable in a bracket list is only integer. if "bracket_indices" in parsed: variable = parsed["variable"] indices = parsed["bracket_indices"] return ["At", variable, *indices] # Flatten binary operations like 1 + 2 + 3 into ["Add", 1, 2, 3] # Last check is to make sure that in cases like ["Max", ["x", "y", ...]] the 'y' is not confused to # be an operator. num_binary_elements = 3 if ( len(parsed) >= num_binary_elements and isinstance(parsed[1], str) and parsed[1] in InfixExpressionParser.BINARY_OPERATORS ): # The chain alternates operands and operators of one precedence level, e.g., # [a, '/', b, '*', c]. Fold it from the left: while the operator stays the # same, extend the current n-ary node; when it changes, the node built so # far becomes the first operand of a new node, so that 'a / b * c' is # (a / b) * c and not a / (b * c). Subtraction is addition of a negated # operand, so '+' and '-' share one 'Add' node. expression = self._to_math_json(parsed[0]) current_operator = None for i in range(1, len(parsed) - 1, 2): op = parsed[i] operand = self._to_math_json(parsed[i + 1]) if op == "-": operator = "Add" operand = ["Negate", operand] else: operator = self.operator_mapping[op] if operator == current_operator: expression.append(operand) else: expression = [operator, expression, operand] current_operator = operator return [expression] # Handle unary operations and functions if isinstance(parsed[0], str) and parsed[0] in self.reserved_symbols: if parsed[0] in self.operator_mapping: operator = self.operator_mapping.get(parsed[0], parsed[0]) operands = [self._to_math_json(p) for p in parsed[1:]] while isinstance(operands, list) and len(operands) == 1 and isinstance(operands[0], list): operands = operands[0] return [operator, [*operands]] operand = self._to_math_json(parsed[1]) return [parsed[0], operand] # For lists and nested expressions return [self._to_math_json(part) for part in parsed] def _remove_extra_brackets(self, lst: list) -> list: """Removes recursively extra brackets from a nested list that may have been left when parsing an expression. Args: lst (list): A (nested) list that needs extra bracket removal. Returns: list: A list with extra brackets removed. """ # Base case: if it's not a list, just return the item itself if not isinstance(lst, list): return lst # If the list has only one element and that element is a list, unpack it if len(lst) == 1 and (isinstance(lst[0], list) or self._is_number_or_variable(lst[0])): return self._remove_extra_brackets(lst[0]) # Otherwise, process each element of the list return [self._remove_extra_brackets(item) for item in lst] def parse(self, str_expr: str) -> list: """The method to call when parsing an infix expression in represented by a string. Args: str_expr (str): A string expression to be parsed. Returns: list: A list representing the parsed expression. """ expr = self._remove_extra_brackets(self.parse_to_target(self.pre_parse(str_expr))) # if the expression is just a string after removing extra brackets, # wrap it in a list to keep the return type consistent. # simple expressions, like 'x_1', are parsed into just a string after removing any extra # brackets, so we add them back there in case it is needed return expr if isinstance(expr, list) else [expr] ``` ##### __init__ ``` __init__(target='MathJSON') ``` A parser for infix notation, e.g., the huma readable way of notating mathematical expressions. The parser can parse infix notation stored in a string to different formats. For instance, "Cos(2 + f_1) - 7.2 + Max(f_2, -f_3)" is first parsed to the list: \['Cos', \[[2, '+', 'f_1']\]\], '-', 7.2, '+', \['Max', \['f_2', ['-', 'f_3']\]. Then, if parsed to the MathJSON format, it will be parsed to the list: \[ \[\["Subtract", \["Cos", ["Add", 2, "f_1"]\], \["Add", 7.2, \["Max", \["f_2", ["Negate", "f_3"]\]\]\]\]\] \]. Parameters: | Name | Type | Description | Default | | -------- | ----- | ------------------------------------------------------------------------------------------------------------------ | ------------ | | `target` | `str` | The target format to parse an infix expression to. Currently only "MathJSON" is supported. Defaults to "MathJSON". | `'MathJSON'` | Source code in `desdeo/problem/infix_parser.py` ``` def __init__(self, target="MathJSON"): """A parser for infix notation, e.g., the huma readable way of notating mathematical expressions. The parser can parse infix notation stored in a string to different formats. For instance, "Cos(2 + f_1) - 7.2 + Max(f_2, -f_3)" is first parsed to the list: ['Cos', [[2, '+', 'f_1']]], '-', 7.2, '+', ['Max', ['f_2', ['-', 'f_3']]. Then, if parsed to the MathJSON format, it will be parsed to the list: [ [["Subtract", ["Cos", ["Add", 2, "f_1"]], ["Add", 7.2, ["Max", ["f_2", ["Negate", "f_3"]]]]]] ]. Args: target (str, optional): The target format to parse an infix expression to. Currently only "MathJSON" is supported. Defaults to "MathJSON". """ if target not in InfixExpressionParser.SUPPORTED_TARGETS: msg = f"The target '{target} is not supported. Should be one of {InfixExpressionParser.SUPPORTED_TARGETS}" raise ValueError(msg) self.target = target # Scope limiters lparen = Suppress("(") rparen = Suppress(")") lbracket = Suppress("[") rbracket = Suppress("]") # Define keywords (Note that binary operators must be defined manually) symbols_variadic = set(InfixExpressionParser.VARIADIC_OPERATORS) symbols_unary = set(InfixExpressionParser.UNARY_OPERATORS) # Define binary operation symbols (this is the manual part) # If new binary operators are to be added, they must be defined here. signop = one_of("+ -") multop = one_of("* / . @") plusop = one_of("+ -") expop = Literal("**") # Dynamically create Keyword objects for variadric functions variadic_pattern = r"\b(" + f"{'|'.join([*symbols_variadic])}" + r")\b" variadic_func_names = Regex(variadic_pattern) # Dynamically create Keyword objects for unary functions # unary_func_names = reduce(or_, (Keyword(k) for k in symbols_unary)) unary_pattern = r"\b(" + f"{'|'.join([*symbols_unary])}" + r")\b" unary_func_names = Regex(unary_pattern) # Define operands integer = pyparsing_common.integer # Scientific notation scientific = pyparsing_common.sci_real # Complete regex pattern with exclusions and identifier pattern exclude = f"{'|'.join([*symbols_variadic, *symbols_unary])}" pattern = r"(?!\b(" + exclude + r")\b)(\b[a-zA-Z_][a-zA-Z0-9_]*\b)" variable = Regex(pattern)("variable") # Forward declarations of variadic, unary, and bracket function calls variadic_call = Forward() unary_call = Forward() bracket_access = Forward() operands = variable | scientific | integer # Define bracket access. Brackets following a variable may contain only integer values. index_list = Group(DelimitedList(integer))("bracket_indices") bracket_access <<= Group(variable + lbracket + index_list + rbracket) # The parsed expressions are assumed to follow a standard infix syntax. The operands # of the infix syntax can be either the literal 'operands' defined above (these are singletons), # or either a variadic function call or a unary function call. These latter two will be # defined to be recursive. # # Note that the order of the operators in the second argument (the list) of infixNotation matters! # The operation with the highest precedence is listed first. infix_expn = infix_notation( bracket_access | operands | variadic_call | unary_call, [ (expop, 2, OpAssoc.LEFT), (signop, 1, OpAssoc.RIGHT), (multop, 2, OpAssoc.LEFT), (plusop, 2, OpAssoc.LEFT), ], )("binary_operator") # These are recursive definitions of the forward declarations of the two type of function calls. # In essence, the recursion continues until a singleton operand is encountered. variadic_call <<= Group(variadic_func_names + lparen + Group(DelimitedList(infix_expn)) + rparen)( "variadic_call" ) unary_call <<= Group(unary_func_names + lparen + Group(infix_expn) + rparen)("unary_call") self.expn = infix_expn # The infix operations do not need to be in this list because they are handled by infixNotation() above. # If new binary operations are to be added, they must be updated in the infixNotation() call (the list). self.reserved_symbols: set[str] = symbols_unary | symbols_variadic # It is assumed that the dicts in the three class variables have unique keys. self.operator_mapping = { **InfixExpressionParser.BINARY_OPERATORS, **InfixExpressionParser.UNARY_OPERATORS, **InfixExpressionParser.VARIADIC_OPERATORS, } if self.target == "MathJSON": self.pre_parse = self._pre_parse self.parse_to_target = self._to_math_json else: self.pre_parse = None self.parse_to_target = None ``` ##### \_remove_extra_brackets ``` _remove_extra_brackets(lst: list) -> list ``` Removes recursively extra brackets from a nested list that may have been left when parsing an expression. Parameters: | Name | Type | Description | Default | | ----- | ------ | ------------------------------------------------- | ---------- | | `lst` | `list` | A (nested) list that needs extra bracket removal. | *required* | Returns: | Name | Type | Description | | ------ | ------ | ----------------------------------- | | `list` | `list` | A list with extra brackets removed. | Source code in `desdeo/problem/infix_parser.py` ``` def _remove_extra_brackets(self, lst: list) -> list: """Removes recursively extra brackets from a nested list that may have been left when parsing an expression. Args: lst (list): A (nested) list that needs extra bracket removal. Returns: list: A list with extra brackets removed. """ # Base case: if it's not a list, just return the item itself if not isinstance(lst, list): return lst # If the list has only one element and that element is a list, unpack it if len(lst) == 1 and (isinstance(lst[0], list) or self._is_number_or_variable(lst[0])): return self._remove_extra_brackets(lst[0]) # Otherwise, process each element of the list return [self._remove_extra_brackets(item) for item in lst] ``` ##### \_to_math_json ``` _to_math_json(parsed: list | str) -> list ``` Converts a list of expressions into a MathJSON compliant format. The conversion happens recursively. Each list of recursed until a terminal character is reached. Terminal characters are integers (int), floating point numbers (float), or non-keyword strings (str). Keyword strings are reserved for operations, such as 'Cos' or 'Max'. Parameters: | Name | Type | Description | Default | | -------- | ------ | ----------------------------------------------------------------------------- | ---------- | | `parsed` | `list` | A list possibly containing other lists. Represents a mathematical expression. | *required* | Returns: | Name | Type | Description | | ------ | ------ | ----------------------------------------------------------------------------- | | `list` | `list` | A list representing a mathematical expression in a MathJSON compliant format. | Source code in `desdeo/problem/infix_parser.py` ``` def _to_math_json(self, parsed: list | str) -> list: """Converts a list of expressions into a MathJSON compliant format. The conversion happens recursively. Each list of recursed until a terminal character is reached. Terminal characters are integers (int), floating point numbers (float), or non-keyword strings (str). Keyword strings are reserved for operations, such as 'Cos' or 'Max'. Args: parsed (list): A list possibly containing other lists. Represents a mathematical expression. Returns: list: A list representing a mathematical expression in a MathJSON compliant format. """ # Directly return the input if it is an integer or a float if self._is_number_or_variable(parsed): return parsed # Handle bracket access # Assume that anything following variable in a bracket list is only integer. if "bracket_indices" in parsed: variable = parsed["variable"] indices = parsed["bracket_indices"] return ["At", variable, *indices] # Flatten binary operations like 1 + 2 + 3 into ["Add", 1, 2, 3] # Last check is to make sure that in cases like ["Max", ["x", "y", ...]] the 'y' is not confused to # be an operator. num_binary_elements = 3 if ( len(parsed) >= num_binary_elements and isinstance(parsed[1], str) and parsed[1] in InfixExpressionParser.BINARY_OPERATORS ): # The chain alternates operands and operators of one precedence level, e.g., # [a, '/', b, '*', c]. Fold it from the left: while the operator stays the # same, extend the current n-ary node; when it changes, the node built so # far becomes the first operand of a new node, so that 'a / b * c' is # (a / b) * c and not a / (b * c). Subtraction is addition of a negated # operand, so '+' and '-' share one 'Add' node. expression = self._to_math_json(parsed[0]) current_operator = None for i in range(1, len(parsed) - 1, 2): op = parsed[i] operand = self._to_math_json(parsed[i + 1]) if op == "-": operator = "Add" operand = ["Negate", operand] else: operator = self.operator_mapping[op] if operator == current_operator: expression.append(operand) else: expression = [operator, expression, operand] current_operator = operator return [expression] # Handle unary operations and functions if isinstance(parsed[0], str) and parsed[0] in self.reserved_symbols: if parsed[0] in self.operator_mapping: operator = self.operator_mapping.get(parsed[0], parsed[0]) operands = [self._to_math_json(p) for p in parsed[1:]] while isinstance(operands, list) and len(operands) == 1 and isinstance(operands[0], list): operands = operands[0] return [operator, [*operands]] operand = self._to_math_json(parsed[1]) return [parsed[0], operand] # For lists and nested expressions return [self._to_math_json(part) for part in parsed] ``` ##### parse ``` parse(str_expr: str) -> list ``` The method to call when parsing an infix expression in represented by a string. Parameters: | Name | Type | Description | Default | | ---------- | ----- | --------------------------------- | ---------- | | `str_expr` | `str` | A string expression to be parsed. | *required* | Returns: | Name | Type | Description | | ------ | ------ | ------------------------------------------ | | `list` | `list` | A list representing the parsed expression. | Source code in `desdeo/problem/infix_parser.py` ``` def parse(self, str_expr: str) -> list: """The method to call when parsing an infix expression in represented by a string. Args: str_expr (str): A string expression to be parsed. Returns: list: A list representing the parsed expression. """ expr = self._remove_extra_brackets(self.parse_to_target(self.pre_parse(str_expr))) # if the expression is just a string after removing extra brackets, # wrap it in a list to keep the return type consistent. # simple expressions, like 'x_1', are parsed into just a string after removing any extra # brackets, so we add them back there in case it is needed return expr if isinstance(expr, list) else [expr] ``` ## Generic evaluator ### desdeo.problem.evaluator Defines a Polars-based evaluator. #### PolarsEvaluator A class for creating Polars-based evaluators for multiobjective optimization problems. The evaluator is to be used with different optimizers. PolarsEvaluator is specifically for solvers that do not require an exact formulation of the problem, but rather work solely on the input and output values of the problem being solved. This evaluator might not be suitable for computationally expensive problems, or mixed-integer problems. This evaluator is suitable for many Python-based solvers. Source code in `desdeo/problem/evaluator.py` ``` class PolarsEvaluator: """A class for creating Polars-based evaluators for multiobjective optimization problems. The evaluator is to be used with different optimizers. PolarsEvaluator is specifically for solvers that do not require an exact formulation of the problem, but rather work solely on the input and output values of the problem being solved. This evaluator might not be suitable for computationally expensive problems, or mixed-integer problems. This evaluator is suitable for many Python-based solvers. """ ### Initialization (no need for decision variables yet) # 1. Create a math parser with parser type 'evaluator_type'. Defaults to 'polars'. # 2. Check for any constants in the definition of the problem. Replace the constants, if they exist, # with their numerical values in all the function expressions found in problem. # 3. Parse the function expressions into a dataframe. ### Evaluating (we have decision variables to evaluate problem) # 1. Evaluate the extra functions (if any) in the dataframe with the decision variables. Store the results # in new columns of the dataframe. # 2. Evaluate the objective functions based on the decision variables and the extra function values (if any). # Store the results in the dataframe in their own columns. # 3. Evalute the scalarization functions (if any) based on the objective function values and extra function values # (if any). Store the results in the dataframe in their own columns. # 4. Evaluate the constraints (if any) last, so that a constraint may reference any of the above. # Nothing else is expected to reference a constraint. Store the results in their own columns. # 5. Return a pydantic dataclass with the results (decision variables, objective function values, constraint values, # and scalarization function valeus). # 6. End. def __init__(self, problem: Problem, evaluator_mode: PolarsEvaluatorModesEnum = PolarsEvaluatorModesEnum.variables): """Create a Polars-based evaluator for a multiobjective optimization problem. By default, the evaluator expects a set of decision variables to evaluate the given problem. However, if the problem is purely based on data (e.g., it represents an approximation of a Pareto optimal front), then the evaluator should be run in 'discrete' mode instead. In this mode, it will return the whole problem with all of its objectives, constraints, and scalarization functions evaluated with the current data representing the problem. Args: problem (Problem): The problem as a pydantic 'Problem' data class. evaluator_mode (str): The mode of evaluator used to parse the problem into a format that can be evaluated. Default 'variables'. """ # Create a MathParser of type 'evaluator_type'. if evaluator_mode not in PolarsEvaluatorModesEnum: msg = ( f"The provided 'evaluator_mode' '{evaluator_mode}' is not supported." f" Must be one of {PolarsEvaluatorModesEnum}." ) raise PolarsEvaluatorError(msg) self.evaluator_mode = evaluator_mode self.problem = problem # Gather any constants of the problem definition. self.problem_constants = problem.constants # Gather the objective functions if evaluator_mode == PolarsEvaluatorModesEnum.mixed: self.problem_objectives = [ objective for objective in problem.objectives if objective.objective_type in [ObjectiveTypeEnum.analytical, ObjectiveTypeEnum.data_based] ] else: self.problem_objectives = problem.objectives # Gather any constraints self.problem_constraints = problem.constraints # Gather any extra functions self.problem_extra = problem.extra_funcs # Gather any scalarization functions self.problem_scalarization = problem.scalarization_funcs # Gather the decision variable symbols defined in the problem self.problem_variable_symbols = [var.symbol for var in problem.variables] # The discrete definition of (some) objectives self.discrete_representation = problem.discrete_representation # The below 'expressions' are list of tuples with symbol and expressions pairs, as (symbol, expression) # These must be defined in a specialized initialization step, see further below for an example. # Symbol and expressions pairs of the objective functions self.objective_expressions = None # Symbol and expressions pairs of any constraints self.constraint_expressions = None # Symbol and expressions pairs of any extra functions self.extra_expressions = None # Symbol and expression pairs of any scalarization functions self.scalarization_expressions = None # Store TensorConstants in a dict self.tensor_constants = None # Note: `self.parser` is assumed to be set before continuing the initialization. self.parser = MathParser() self._polars_init() # Note, when calling an evaluate method, it is assumed the problem has been fully parsed. if self.evaluator_mode in [PolarsEvaluatorModesEnum.variables, PolarsEvaluatorModesEnum.mixed]: self.evaluate = self._polars_evaluate self.evaluate_flat = self._polars_evaluate_flat elif self.evaluator_mode == PolarsEvaluatorModesEnum.discrete: self.evaluate = self._from_discrete_data else: msg = ( f"Provided 'evaluator_mode' {evaluator_mode} not supported. Must be one of {PolarsEvaluatorModesEnum}." ) def _polars_init(self): # noqa: C901 """Initialization of the evaluator for parser type 'polars'.""" # If any constants are defined in problem, replace their symbol with the defined numerical # value in all the function expressions found in the Problem. if self.problem_constants is not None: # Objectives are always defined, cannot be None parsed_obj_funcs = {} for obj in self.problem_objectives: if obj.objective_type == ObjectiveTypeEnum.analytical: # if analytical proceed with replacing the symbols. tmp = obj.func # replace regular constants, skip TensorConstants for c in self.problem_constants: if isinstance(c, Constant): tmp = replace_str(tmp, c.symbol, c.value) parsed_obj_funcs[f"{obj.symbol}"] = tmp elif obj.objective_type == ObjectiveTypeEnum.data_based: # data-based objective parsed_obj_funcs[f"{obj.symbol}"] = None else: msg = ( f"Incorrect objective-type {obj.objective_type} encountered. Must be one of {ObjectiveTypeEnum}" ) raise PolarsEvaluatorError(msg) # Do the same for any constraint expressions as well. if self.problem_constraints is not None: parsed_cons_funcs: dict | None = {} for con in self.problem_constraints: tmp = con.func # replace regular constants, skip TensorConstants for c in self.problem_constants: if isinstance(c, Constant): tmp = replace_str(tmp, c.symbol, c.value) parsed_cons_funcs[f"{con.symbol}"] = tmp else: parsed_cons_funcs = None # Do the same for any extra functions parsed_extra_funcs: dict | None = {} if self.problem_extra is not None: for extra in self.problem_extra: tmp = extra.func # replace regular constants, skip TensorConstants for c in self.problem_constants: if isinstance(c, Constant): tmp = replace_str(tmp, c.symbol, c.value) parsed_extra_funcs[f"{extra.symbol}"] = tmp else: parsed_extra_funcs = None # Do the same for any scalarization functions parsed_scal_funcs: dict | None = {} if self.problem_scalarization is not None: for scal in self.problem_scalarization: tmp = scal.func # replace regular constants, skip TensorConstants for c in self.problem_constants: if isinstance(c, Constant): tmp = replace_str(tmp, c.symbol, c.value) parsed_scal_funcs[f"{scal.symbol}"] = tmp else: parsed_scal_funcs = None # Check for TensorConstants for c in self.problem_constants: if isinstance(c, TensorConstant): if self.tensor_constants is None: self.tensor_constants = {} self.tensor_constants[c.symbol] = np.array(c.get_values()) else: # no constants defined, just collect all expressions as they are parsed_obj_funcs = {f"{objective.symbol}": objective.func for objective in self.problem_objectives} if self.problem_constraints is not None: parsed_cons_funcs = {f"{constraint.symbol}": constraint.func for constraint in self.problem_constraints} else: parsed_cons_funcs = None if self.problem_extra is not None: parsed_extra_funcs = {f"{extra.symbol}": extra.func for extra in self.problem_extra} else: parsed_extra_funcs = None if self.problem_scalarization is not None: parsed_scal_funcs = {f"{scal.symbol}": scal.func for scal in self.problem_scalarization} else: parsed_scal_funcs = None # Parse all functions into expressions. These are stored as tuples, as (symbol, parsed expression) # parse objectives # If no expression is given (data-based objective, then the expression is set to be 'None') self.objective_expressions = [ (symbol, self.parser.parse(expression)) if expression is not None else (symbol, None) for symbol, expression in parsed_obj_funcs.items() ] # parse extra functions, if any # if an extra function is simulator or surrogate based (expression is None), set the "parsed" expression as None if parsed_extra_funcs is not None: self.extra_expressions = [ (symbol, self.parser.parse(expression)) if expression is not None else (symbol, None) for symbol, expression in parsed_extra_funcs.items() ] else: self.extra_expressions = None # parse scalarization functions, if any if parsed_scal_funcs is not None: self.scalarization_expressions = [ (symbol, self.parser.parse(expression)) for symbol, expression in parsed_scal_funcs.items() ] else: self.scalarization_expressions = None # parse constraints, if any # if a constraint is simulator or surrogate based (expression is None), set the "parsed" expression as None if parsed_cons_funcs is not None: self.constraint_expressions = [ (symbol, self.parser.parse(expression)) if expression is not None else (symbol, None) for symbol, expression in parsed_cons_funcs.items() ] else: self.constraint_expressions = None # store the symbol and min or max multiplier as well (symbol, min/max multiplier [1 | -1]) self.objective_mix_max_mult = [ (objective.symbol, -1 if objective.maximize else 1) for objective in self.problem_objectives ] # create dataframe with the discrete representation, if any exists if self.discrete_representation is not None: self.discrete_df = pl.DataFrame( {**self.discrete_representation.variable_values, **self.discrete_representation.objective_values} ) else: self.discrete_df = None def _polars_evaluate( self, xs: pl.DataFrame | dict[str, list[float | int | bool]], ) -> pl.DataFrame: """Evaluate the problem with the given decision variable values utilizing a polars dataframe. Args: xs (pl.DataFrame | dict[str, list[float | int | bool]]): a Polars dataframe or dict with the decision variable symbols as the columns (keys) followed by the corresponding decision variable values stored in an array (list). The symbols must match the symbols defined for the decision variables defined in the `Problem` being solved. Each column (list) in the dataframe (dict) should contain the same number of values. Returns: pl.DataFrame: the polars dataframe with the computed results. Note: At least `self.objective_expressions` must be defined before calling this method. """ # An aggregate dataframe to store intermediate evaluation results. # agg_df = pl.DataFrame({key: np.array(value) for key, value in xs.items()}) agg_df = pl.DataFrame( xs, schema=[ (var.symbol, pl.Float64 if isinstance(var, Variable) else pl.Array(pl.Float64, tuple(var.shape))) for var in self.problem.variables ], ) # need to make sure to provide schema for tensor variables of type Array # Deal with TensorConstant # agg_df.with_columns(pl.Series(np.array(2*[self.tensor_constants["W"]])).alias("W")) if self.tensor_constants is not None: for tc_symbol in self.tensor_constants: agg_df = agg_df.with_columns( pl.Series(np.array(agg_df.height * [self.tensor_constants[tc_symbol]])).alias(tc_symbol) ) # Evaluate any extra functions and put the results in the aggregate dataframe. # If an extra function is simulator or surrogate based (expression None), skip it here if self.extra_expressions is not None: for symbol, expr in self.extra_expressions: if expr is not None: # expression given extra_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(extra_column) # Evaluate the objective functions and put the results in the aggregate dataframe. # obj_columns = agg_df.select(*[expr.alias(symbol) for symbol, expr in self.objective_expressions]) # agg_df = agg_df.hstack(obj_columns) for symbol, expr in self.objective_expressions: if expr is not None: # expression given obj_col = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(obj_col) # elif self.evaluator_mode != PolarsEvaluatorModesEnum.mixed: else: # expr is None and there are no no simulator or surrogate based objectives, # therefore we must get the objective function's value somehow else, usually from data obj_col = find_closest_points(agg_df, self.discrete_df, self.problem_variable_symbols, symbol) agg_df = agg_df.hstack(obj_col) # Evaluate the minimization form of the objective functions # Note that the column name of these should be 'the objective function's symbol'_min # e.g., 'f_1' -> 'f_1_min' min_obj_columns = agg_df.select( *[ (min_max_mult * pl.col(f"{symbol}")).alias(f"{symbol}_min") for symbol, min_max_mult in self.objective_mix_max_mult ] ) agg_df = agg_df.hstack(min_obj_columns) # Evaluate any scalarization functions and put the result in the aggregate dataframe. # Evaluated one at a time so that a scalarization function may reference one # defined before it, as objectives, extra functions and constraints already can. if self.scalarization_expressions is not None: for symbol, expr in self.scalarization_expressions: scal_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(scal_column) # Evaluate any constraints and put the results in the aggregate dataframe # If a constraint is simulator or surrogate based (expression None), skip it here if self.constraint_expressions is not None: for symbol, expr in self.constraint_expressions: if expr is not None: # expression given cons_columns = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(cons_columns) # return the dataframe and let the solver figure it out return agg_df def _polars_evaluate_flat( self, xs: pl.DataFrame | dict[str, list[float | int | bool]], ) -> pl.DataFrame: """Evaluate the problem with flattened variables. Args: xs (pl.DataFrame | dict[str, list[float | int | bool]]): a polars dataframe or dict with flattened variables. E.g., if the original problem has a tensor variable 'X' with shape (2,2), then the input is expected to have entries with columns (keys) 'X_1_1', 'X_1_2', 'X_2_1', and 'X_2_2'. The input is rebuilt and passed to `self._evaluate`. Note: Each flattened variable is assumed to contain the same number of samples. This means that if the entry 'X_1_1' of `xs` is, for example `[1,2,3]`, this means that 'X_1_1' and all the other flattened variables have three samples. This means also that the original problem will be evaluated with a tensor variable with shape (2,2) and three samples, e.g., 'X=[[[1, 1], [1,1]], [[2, 2], [2, 2]], [[3, 3], [3, 3]]]'. Returns: pl.DataFrame: a dataframe with the original problem's evaluated functions. """ # Assume all variables have the same number of samples if isinstance(xs, dict): xs = pl.DataFrame(xs) if not any(isinstance(var, TensorVariable) for var in self.problem.variables): # Nothing to rebuild: select the variables in one operation rather than one per variable. return self.evaluate(xs.select([var.symbol for var in self.problem.variables])) unflattened_xs = pl.DataFrame() # iterate over the variables of the problem for var in self.problem.variables: if isinstance(var, TensorVariable): # construct the tensor variable unflattened_xs = unflattened_xs.with_columns( xs.select(pl.concat_arr(f"^{var.symbol}_.*$").alias(var.symbol).reshape((-1, *var.shape))) ) else: # else, proceed normally unflattened_xs = unflattened_xs.with_columns(xs[var.symbol]) # return result of regular evaluate return self.evaluate(unflattened_xs) def _from_discrete_data(self) -> pl.DataFrame: """Evaluates the problem based on its discrete representation only. Assumes that all the objective functions in the problem are of type 'data-based'. In this case, the problem is evaluated based on its current discrete representation. Therefore, no decision variable values are expected. Returns: pl.DataFrame: a polars dataframe with the evaluation results. """ agg_df = self.discrete_df.clone() # Evaluate any extra functions and put the results in the aggregate dataframe. # Evaluated one at a time so that an extra function may reference one defined before it. if self.extra_expressions is not None: for symbol, expr in self.extra_expressions: extra_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(extra_column) # Evaluate the minimization form of the objective functions # Note that the column name of these should be 'the objective function's symbol'_min # e.g., 'f_1' -> 'f_1_min' min_obj_columns = agg_df.select( *[ (min_max_mult * pl.col(f"{symbol}")).alias(f"{symbol}_min") for symbol, min_max_mult in self.objective_mix_max_mult ] ) agg_df = agg_df.hstack(min_obj_columns) # Evaluate any scalarization functions and put the result in the aggregate dataframe. # Evaluated one at a time so that a scalarization function may reference one defined before it. if self.scalarization_expressions is not None: for symbol, expr in self.scalarization_expressions: scal_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(scal_column) # Evaluate any constraints and put the results in the aggregate dataframe. # Evaluated one at a time so that a constraint may reference one defined before it. if self.constraint_expressions is not None: for symbol, expr in self.constraint_expressions: cons_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(cons_column) # no more processing needed, it is assumed a solver will handle the rest return agg_df ``` ##### __init__ ``` __init__( problem: Problem, evaluator_mode: PolarsEvaluatorModesEnum = PolarsEvaluatorModesEnum.variables, ) ``` Create a Polars-based evaluator for a multiobjective optimization problem. By default, the evaluator expects a set of decision variables to evaluate the given problem. However, if the problem is purely based on data (e.g., it represents an approximation of a Pareto optimal front), then the evaluator should be run in 'discrete' mode instead. In this mode, it will return the whole problem with all of its objectives, constraints, and scalarization functions evaluated with the current data representing the problem. Parameters: | Name | Type | Description | Default | | ---------------- | --------- | --------------------------------------------------------------------------------------------------------- | ----------- | | `problem` | `Problem` | The problem as a pydantic 'Problem' data class. | *required* | | `evaluator_mode` | `str` | The mode of evaluator used to parse the problem into a format that can be evaluated. Default 'variables'. | `variables` | Source code in `desdeo/problem/evaluator.py` ``` def __init__(self, problem: Problem, evaluator_mode: PolarsEvaluatorModesEnum = PolarsEvaluatorModesEnum.variables): """Create a Polars-based evaluator for a multiobjective optimization problem. By default, the evaluator expects a set of decision variables to evaluate the given problem. However, if the problem is purely based on data (e.g., it represents an approximation of a Pareto optimal front), then the evaluator should be run in 'discrete' mode instead. In this mode, it will return the whole problem with all of its objectives, constraints, and scalarization functions evaluated with the current data representing the problem. Args: problem (Problem): The problem as a pydantic 'Problem' data class. evaluator_mode (str): The mode of evaluator used to parse the problem into a format that can be evaluated. Default 'variables'. """ # Create a MathParser of type 'evaluator_type'. if evaluator_mode not in PolarsEvaluatorModesEnum: msg = ( f"The provided 'evaluator_mode' '{evaluator_mode}' is not supported." f" Must be one of {PolarsEvaluatorModesEnum}." ) raise PolarsEvaluatorError(msg) self.evaluator_mode = evaluator_mode self.problem = problem # Gather any constants of the problem definition. self.problem_constants = problem.constants # Gather the objective functions if evaluator_mode == PolarsEvaluatorModesEnum.mixed: self.problem_objectives = [ objective for objective in problem.objectives if objective.objective_type in [ObjectiveTypeEnum.analytical, ObjectiveTypeEnum.data_based] ] else: self.problem_objectives = problem.objectives # Gather any constraints self.problem_constraints = problem.constraints # Gather any extra functions self.problem_extra = problem.extra_funcs # Gather any scalarization functions self.problem_scalarization = problem.scalarization_funcs # Gather the decision variable symbols defined in the problem self.problem_variable_symbols = [var.symbol for var in problem.variables] # The discrete definition of (some) objectives self.discrete_representation = problem.discrete_representation # The below 'expressions' are list of tuples with symbol and expressions pairs, as (symbol, expression) # These must be defined in a specialized initialization step, see further below for an example. # Symbol and expressions pairs of the objective functions self.objective_expressions = None # Symbol and expressions pairs of any constraints self.constraint_expressions = None # Symbol and expressions pairs of any extra functions self.extra_expressions = None # Symbol and expression pairs of any scalarization functions self.scalarization_expressions = None # Store TensorConstants in a dict self.tensor_constants = None # Note: `self.parser` is assumed to be set before continuing the initialization. self.parser = MathParser() self._polars_init() # Note, when calling an evaluate method, it is assumed the problem has been fully parsed. if self.evaluator_mode in [PolarsEvaluatorModesEnum.variables, PolarsEvaluatorModesEnum.mixed]: self.evaluate = self._polars_evaluate self.evaluate_flat = self._polars_evaluate_flat elif self.evaluator_mode == PolarsEvaluatorModesEnum.discrete: self.evaluate = self._from_discrete_data else: msg = ( f"Provided 'evaluator_mode' {evaluator_mode} not supported. Must be one of {PolarsEvaluatorModesEnum}." ) ``` ##### \_from_discrete_data ``` _from_discrete_data() -> pl.DataFrame ``` Evaluates the problem based on its discrete representation only. Assumes that all the objective functions in the problem are of type 'data-based'. In this case, the problem is evaluated based on its current discrete representation. Therefore, no decision variable values are expected. Returns: | Type | Description | | ----------- | ------------------------------------------------------------- | | `DataFrame` | pl.DataFrame: a polars dataframe with the evaluation results. | Source code in `desdeo/problem/evaluator.py` ``` def _from_discrete_data(self) -> pl.DataFrame: """Evaluates the problem based on its discrete representation only. Assumes that all the objective functions in the problem are of type 'data-based'. In this case, the problem is evaluated based on its current discrete representation. Therefore, no decision variable values are expected. Returns: pl.DataFrame: a polars dataframe with the evaluation results. """ agg_df = self.discrete_df.clone() # Evaluate any extra functions and put the results in the aggregate dataframe. # Evaluated one at a time so that an extra function may reference one defined before it. if self.extra_expressions is not None: for symbol, expr in self.extra_expressions: extra_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(extra_column) # Evaluate the minimization form of the objective functions # Note that the column name of these should be 'the objective function's symbol'_min # e.g., 'f_1' -> 'f_1_min' min_obj_columns = agg_df.select( *[ (min_max_mult * pl.col(f"{symbol}")).alias(f"{symbol}_min") for symbol, min_max_mult in self.objective_mix_max_mult ] ) agg_df = agg_df.hstack(min_obj_columns) # Evaluate any scalarization functions and put the result in the aggregate dataframe. # Evaluated one at a time so that a scalarization function may reference one defined before it. if self.scalarization_expressions is not None: for symbol, expr in self.scalarization_expressions: scal_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(scal_column) # Evaluate any constraints and put the results in the aggregate dataframe. # Evaluated one at a time so that a constraint may reference one defined before it. if self.constraint_expressions is not None: for symbol, expr in self.constraint_expressions: cons_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(cons_column) # no more processing needed, it is assumed a solver will handle the rest return agg_df ``` ##### \_polars_evaluate ``` _polars_evaluate( xs: DataFrame | dict[str, list[float | int | bool]], ) -> pl.DataFrame ``` Evaluate the problem with the given decision variable values utilizing a polars dataframe. Parameters: | Name | Type | Description | Default | | ---- | ----------- | ---------------------- | ------- | | `xs` | \`DataFrame | dict\[str, list\[float | int | Returns: | Type | Description | | ----------- | ------------------------------------------------------------- | | `DataFrame` | pl.DataFrame: the polars dataframe with the computed results. | Note At least `self.objective_expressions` must be defined before calling this method. Source code in `desdeo/problem/evaluator.py` ``` def _polars_evaluate( self, xs: pl.DataFrame | dict[str, list[float | int | bool]], ) -> pl.DataFrame: """Evaluate the problem with the given decision variable values utilizing a polars dataframe. Args: xs (pl.DataFrame | dict[str, list[float | int | bool]]): a Polars dataframe or dict with the decision variable symbols as the columns (keys) followed by the corresponding decision variable values stored in an array (list). The symbols must match the symbols defined for the decision variables defined in the `Problem` being solved. Each column (list) in the dataframe (dict) should contain the same number of values. Returns: pl.DataFrame: the polars dataframe with the computed results. Note: At least `self.objective_expressions` must be defined before calling this method. """ # An aggregate dataframe to store intermediate evaluation results. # agg_df = pl.DataFrame({key: np.array(value) for key, value in xs.items()}) agg_df = pl.DataFrame( xs, schema=[ (var.symbol, pl.Float64 if isinstance(var, Variable) else pl.Array(pl.Float64, tuple(var.shape))) for var in self.problem.variables ], ) # need to make sure to provide schema for tensor variables of type Array # Deal with TensorConstant # agg_df.with_columns(pl.Series(np.array(2*[self.tensor_constants["W"]])).alias("W")) if self.tensor_constants is not None: for tc_symbol in self.tensor_constants: agg_df = agg_df.with_columns( pl.Series(np.array(agg_df.height * [self.tensor_constants[tc_symbol]])).alias(tc_symbol) ) # Evaluate any extra functions and put the results in the aggregate dataframe. # If an extra function is simulator or surrogate based (expression None), skip it here if self.extra_expressions is not None: for symbol, expr in self.extra_expressions: if expr is not None: # expression given extra_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(extra_column) # Evaluate the objective functions and put the results in the aggregate dataframe. # obj_columns = agg_df.select(*[expr.alias(symbol) for symbol, expr in self.objective_expressions]) # agg_df = agg_df.hstack(obj_columns) for symbol, expr in self.objective_expressions: if expr is not None: # expression given obj_col = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(obj_col) # elif self.evaluator_mode != PolarsEvaluatorModesEnum.mixed: else: # expr is None and there are no no simulator or surrogate based objectives, # therefore we must get the objective function's value somehow else, usually from data obj_col = find_closest_points(agg_df, self.discrete_df, self.problem_variable_symbols, symbol) agg_df = agg_df.hstack(obj_col) # Evaluate the minimization form of the objective functions # Note that the column name of these should be 'the objective function's symbol'_min # e.g., 'f_1' -> 'f_1_min' min_obj_columns = agg_df.select( *[ (min_max_mult * pl.col(f"{symbol}")).alias(f"{symbol}_min") for symbol, min_max_mult in self.objective_mix_max_mult ] ) agg_df = agg_df.hstack(min_obj_columns) # Evaluate any scalarization functions and put the result in the aggregate dataframe. # Evaluated one at a time so that a scalarization function may reference one # defined before it, as objectives, extra functions and constraints already can. if self.scalarization_expressions is not None: for symbol, expr in self.scalarization_expressions: scal_column = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(scal_column) # Evaluate any constraints and put the results in the aggregate dataframe # If a constraint is simulator or surrogate based (expression None), skip it here if self.constraint_expressions is not None: for symbol, expr in self.constraint_expressions: if expr is not None: # expression given cons_columns = agg_df.select(expr.alias(symbol)) agg_df = agg_df.hstack(cons_columns) # return the dataframe and let the solver figure it out return agg_df ``` ##### \_polars_evaluate_flat ``` _polars_evaluate_flat( xs: DataFrame | dict[str, list[float | int | bool]], ) -> pl.DataFrame ``` Evaluate the problem with flattened variables. Parameters: | Name | Type | Description | Default | | ---- | ----------- | ---------------------- | ------- | | `xs` | \`DataFrame | dict\[str, list\[float | int | Note Each flattened variable is assumed to contain the same number of samples. This means that if the entry 'X_1_1' of `xs` is, for example `[1,2,3]`, this means that 'X_1_1' and all the other flattened variables have three samples. This means also that the original problem will be evaluated with a tensor variable with shape (2,2) and three samples, e.g., 'X=\[\[[1, 1], [1,1]\], \[[2, 2], [2, 2]\], \[[3, 3], [3, 3]\]\]'. Returns: | Type | Description | | ----------- | -------------------------------------------------------------------------- | | `DataFrame` | pl.DataFrame: a dataframe with the original problem's evaluated functions. | Source code in `desdeo/problem/evaluator.py` ``` def _polars_evaluate_flat( self, xs: pl.DataFrame | dict[str, list[float | int | bool]], ) -> pl.DataFrame: """Evaluate the problem with flattened variables. Args: xs (pl.DataFrame | dict[str, list[float | int | bool]]): a polars dataframe or dict with flattened variables. E.g., if the original problem has a tensor variable 'X' with shape (2,2), then the input is expected to have entries with columns (keys) 'X_1_1', 'X_1_2', 'X_2_1', and 'X_2_2'. The input is rebuilt and passed to `self._evaluate`. Note: Each flattened variable is assumed to contain the same number of samples. This means that if the entry 'X_1_1' of `xs` is, for example `[1,2,3]`, this means that 'X_1_1' and all the other flattened variables have three samples. This means also that the original problem will be evaluated with a tensor variable with shape (2,2) and three samples, e.g., 'X=[[[1, 1], [1,1]], [[2, 2], [2, 2]], [[3, 3], [3, 3]]]'. Returns: pl.DataFrame: a dataframe with the original problem's evaluated functions. """ # Assume all variables have the same number of samples if isinstance(xs, dict): xs = pl.DataFrame(xs) if not any(isinstance(var, TensorVariable) for var in self.problem.variables): # Nothing to rebuild: select the variables in one operation rather than one per variable. return self.evaluate(xs.select([var.symbol for var in self.problem.variables])) unflattened_xs = pl.DataFrame() # iterate over the variables of the problem for var in self.problem.variables: if isinstance(var, TensorVariable): # construct the tensor variable unflattened_xs = unflattened_xs.with_columns( xs.select(pl.concat_arr(f"^{var.symbol}_.*$").alias(var.symbol).reshape((-1, *var.shape))) ) else: # else, proceed normally unflattened_xs = unflattened_xs.with_columns(xs[var.symbol]) # return result of regular evaluate return self.evaluate(unflattened_xs) ``` ##### \_polars_init ``` _polars_init() ``` Initialization of the evaluator for parser type 'polars'. Source code in `desdeo/problem/evaluator.py` ``` def _polars_init(self): # noqa: C901 """Initialization of the evaluator for parser type 'polars'.""" # If any constants are defined in problem, replace their symbol with the defined numerical # value in all the function expressions found in the Problem. if self.problem_constants is not None: # Objectives are always defined, cannot be None parsed_obj_funcs = {} for obj in self.problem_objectives: if obj.objective_type == ObjectiveTypeEnum.analytical: # if analytical proceed with replacing the symbols. tmp = obj.func # replace regular constants, skip TensorConstants for c in self.problem_constants: if isinstance(c, Constant): tmp = replace_str(tmp, c.symbol, c.value) parsed_obj_funcs[f"{obj.symbol}"] = tmp elif obj.objective_type == ObjectiveTypeEnum.data_based: # data-based objective parsed_obj_funcs[f"{obj.symbol}"] = None else: msg = ( f"Incorrect objective-type {obj.objective_type} encountered. Must be one of {ObjectiveTypeEnum}" ) raise PolarsEvaluatorError(msg) # Do the same for any constraint expressions as well. if self.problem_constraints is not None: parsed_cons_funcs: dict | None = {} for con in self.problem_constraints: tmp = con.func # replace regular constants, skip TensorConstants for c in self.problem_constants: if isinstance(c, Constant): tmp = replace_str(tmp, c.symbol, c.value) parsed_cons_funcs[f"{con.symbol}"] = tmp else: parsed_cons_funcs = None # Do the same for any extra functions parsed_extra_funcs: dict | None = {} if self.problem_extra is not None: for extra in self.problem_extra: tmp = extra.func # replace regular constants, skip TensorConstants for c in self.problem_constants: if isinstance(c, Constant): tmp = replace_str(tmp, c.symbol, c.value) parsed_extra_funcs[f"{extra.symbol}"] = tmp else: parsed_extra_funcs = None # Do the same for any scalarization functions parsed_scal_funcs: dict | None = {} if self.problem_scalarization is not None: for scal in self.problem_scalarization: tmp = scal.func # replace regular constants, skip TensorConstants for c in self.problem_constants: if isinstance(c, Constant): tmp = replace_str(tmp, c.symbol, c.value) parsed_scal_funcs[f"{scal.symbol}"] = tmp else: parsed_scal_funcs = None # Check for TensorConstants for c in self.problem_constants: if isinstance(c, TensorConstant): if self.tensor_constants is None: self.tensor_constants = {} self.tensor_constants[c.symbol] = np.array(c.get_values()) else: # no constants defined, just collect all expressions as they are parsed_obj_funcs = {f"{objective.symbol}": objective.func for objective in self.problem_objectives} if self.problem_constraints is not None: parsed_cons_funcs = {f"{constraint.symbol}": constraint.func for constraint in self.problem_constraints} else: parsed_cons_funcs = None if self.problem_extra is not None: parsed_extra_funcs = {f"{extra.symbol}": extra.func for extra in self.problem_extra} else: parsed_extra_funcs = None if self.problem_scalarization is not None: parsed_scal_funcs = {f"{scal.symbol}": scal.func for scal in self.problem_scalarization} else: parsed_scal_funcs = None # Parse all functions into expressions. These are stored as tuples, as (symbol, parsed expression) # parse objectives # If no expression is given (data-based objective, then the expression is set to be 'None') self.objective_expressions = [ (symbol, self.parser.parse(expression)) if expression is not None else (symbol, None) for symbol, expression in parsed_obj_funcs.items() ] # parse extra functions, if any # if an extra function is simulator or surrogate based (expression is None), set the "parsed" expression as None if parsed_extra_funcs is not None: self.extra_expressions = [ (symbol, self.parser.parse(expression)) if expression is not None else (symbol, None) for symbol, expression in parsed_extra_funcs.items() ] else: self.extra_expressions = None # parse scalarization functions, if any if parsed_scal_funcs is not None: self.scalarization_expressions = [ (symbol, self.parser.parse(expression)) for symbol, expression in parsed_scal_funcs.items() ] else: self.scalarization_expressions = None # parse constraints, if any # if a constraint is simulator or surrogate based (expression is None), set the "parsed" expression as None if parsed_cons_funcs is not None: self.constraint_expressions = [ (symbol, self.parser.parse(expression)) if expression is not None else (symbol, None) for symbol, expression in parsed_cons_funcs.items() ] else: self.constraint_expressions = None # store the symbol and min or max multiplier as well (symbol, min/max multiplier [1 | -1]) self.objective_mix_max_mult = [ (objective.symbol, -1 if objective.maximize else 1) for objective in self.problem_objectives ] # create dataframe with the discrete representation, if any exists if self.discrete_representation is not None: self.discrete_df = pl.DataFrame( {**self.discrete_representation.variable_values, **self.discrete_representation.objective_values} ) else: self.discrete_df = None ``` #### PolarsEvaluatorError Bases: `Exception` Error raised when exceptions are encountered in an PolarsEvaluator. Source code in `desdeo/problem/evaluator.py` ``` class PolarsEvaluatorError(Exception): """Error raised when exceptions are encountered in an PolarsEvaluator.""" ``` #### PolarsEvaluatorModesEnum Bases: `StrEnum` Defines the supported modes for the PolarsEvaluator. Source code in `desdeo/problem/evaluator.py` ``` class PolarsEvaluatorModesEnum(StrEnum): """Defines the supported modes for the PolarsEvaluator.""" variables = "variables" """Indicates that the evaluator should expect decision variables vectors and evaluate the problem with them.""" discrete = "discrete" """Indicates that the problem is defined by discrete decision variable vector and objective vector pairs and those should be evaluated. In this mode, the evaluator does not expect any decision variables as arguments when evaluating.""" mixed = "mixed" """Indicates that the problem has analytical and simulator and/or surrogate based objectives, constraints and extra functions. In this mode, the evaluator only handles data-based and analytical functions. For data-based objectives, it assumes that the variables are to be evaluated by finding the closest variables values in the data compare to the input, and evaluating the result to be the matching objective function values that match to the closest variable values found. The evaluator should expect decision variables vectors and evaluate the problem with them.""" ``` ##### discrete ``` discrete = 'discrete' ``` Indicates that the problem is defined by discrete decision variable vector and objective vector pairs and those should be evaluated. In this mode, the evaluator does not expect any decision variables as arguments when evaluating. ##### mixed ``` mixed = 'mixed' ``` Indicates that the problem has analytical and simulator and/or surrogate based objectives, constraints and extra functions. In this mode, the evaluator only handles data-based and analytical functions. For data-based objectives, it assumes that the variables are to be evaluated by finding the closest variables values in the data compare to the input, and evaluating the result to be the matching objective function values that match to the closest variable values found. The evaluator should expect decision variables vectors and evaluate the problem with them. ##### variables ``` variables = 'variables' ``` Indicates that the evaluator should expect decision variables vectors and evaluate the problem with them. #### VariableDimensionEnum Bases: `StrEnum` An enumerator for the possible dimensions of the variables of a problem. Source code in `desdeo/problem/evaluator.py` ``` class VariableDimensionEnum(StrEnum): """An enumerator for the possible dimensions of the variables of a problem.""" scalar = "scalar" """All variables are scalar valued.""" vector = "vector" """Highest dimensional variable is a vector.""" tensor = "tensor" """Some variable has more dimensions.""" ``` ##### scalar ``` scalar = 'scalar' ``` All variables are scalar valued. ##### tensor ``` tensor = 'tensor' ``` Some variable has more dimensions. ##### vector ``` vector = 'vector' ``` Highest dimensional variable is a vector. #### find_closest_points ``` find_closest_points( xs: DataFrame, discrete_df: DataFrame, variable_symbols: list[str], objective_symbol: list[str], ) -> pl.DataFrame ``` Finds the closest points between the variable columns in xs and discrete_df. For each row in xs, compares the `variable_symbols` columns and find the closest point in `discrete_df`. Returns the objective value in the `objective_symbol` column in `discrete_df` for each variable defined in `xs`, where the objective value corresponds to the closest point of each variable in `xs` compared to `discrete_df`. Both `xs` and `discrete_df` must have the columns `variable_symbols`. `discrete_df` must also have the column `objective_symbol`. Parameters: | Name | Type | Description | Default | | ------------------ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `xs` | `DataFrame` | a polars dataframe with the variable values we are interested in finding the closest corresponding variable values in discrete_df. | *required* | | `discrete_df` | `DataFrame` | a polars dataframe to compare the rows in xs to. | *required* | | `variable_symbols` | `list[str]` | the names of the columns with decision variable values. | *required* | | `objective_symbol` | `str` | the name of the column in discrete_df that has the objective function values. | *required* | Returns: | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `DataFrame` | pl.DataFrame: a dataframe with the columns objective_symbol with the objective function value that corresponds to each decision variable vector in xs. | Source code in `desdeo/problem/evaluator.py` ``` def find_closest_points( xs: pl.DataFrame, discrete_df: pl.DataFrame, variable_symbols: list[str], objective_symbol: list[str] ) -> pl.DataFrame: """Finds the closest points between the variable columns in xs and discrete_df. For each row in xs, compares the `variable_symbols` columns and find the closest point in `discrete_df`. Returns the objective value in the `objective_symbol` column in `discrete_df` for each variable defined in `xs`, where the objective value corresponds to the closest point of each variable in `xs` compared to `discrete_df`. Both `xs` and `discrete_df` must have the columns `variable_symbols`. `discrete_df` must also have the column `objective_symbol`. Args: xs (pl.DataFrame): a polars dataframe with the variable values we are interested in finding the closest corresponding variable values in `discrete_df`. discrete_df (pl.DataFrame): a polars dataframe to compare the rows in `xs` to. variable_symbols (list[str]): the names of the columns with decision variable values. objective_symbol (str): the name of the column in `discrete_df` that has the objective function values. Returns: pl.DataFrame: a dataframe with the columns `objective_symbol` with the objective function value that corresponds to each decision variable vector in `xs`. """ xs_vars_only = xs[variable_symbols] results = [] for row in xs_vars_only.rows(named=True): distance_expr = ( sum((pl.col(var_symbol) - row[var_symbol]) ** 2 for var_symbol in variable_symbols).sqrt().alias("distance") ) combined_df = discrete_df.with_columns(distance_expr) closest = combined_df.sort("distance").head(1) results.append(closest[f"{objective_symbol}"][0]) return pl.DataFrame({f"{objective_symbol}": results}) ``` #### variable_dimension_enumerate ``` variable_dimension_enumerate( problem: Problem, ) -> VariableDimensionEnum ``` Return a VariableDimensionEnum based on the problems variables' dimensions. This is needed as different evaluators and solvers can handle different dimensional variables. If there are no TensorVariables in the problem, will return scalar. If there are, at the highest, one dimensional TensorVariables, will return vector. Else, there is at least a TensorVariable with a higher dimension, will return tensor. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------- | ---------- | | `problem` | `Problem` | The problem being solved or evaluated. | *required* | Returns: | Name | Type | Description | | ----------------------- | ----------------------- | ---------------------------------------------------- | | `VariableDimensionEnum` | `VariableDimensionEnum` | The enumeration of the problems variable dimensions. | Source code in `desdeo/problem/evaluator.py` ``` def variable_dimension_enumerate(problem: Problem) -> VariableDimensionEnum: """Return a VariableDimensionEnum based on the problems variables' dimensions. This is needed as different evaluators and solvers can handle different dimensional variables. If there are no TensorVariables in the problem, will return scalar. If there are, at the highest, one dimensional TensorVariables, will return vector. Else, there is at least a TensorVariable with a higher dimension, will return tensor. Args: problem (Problem): The problem being solved or evaluated. Returns: VariableDimensionEnum: The enumeration of the problems variable dimensions. """ enum = VariableDimensionEnum.scalar for var in problem.variables: if isinstance(var, TensorVariable): if len(var.shape) == 1 or (len(var.shape) == 2 and not (var.shape[0] > 1 and var.shape[1] > 1)): # noqa: PLR2004 enum = VariableDimensionEnum.vector else: return VariableDimensionEnum.tensor return enum ``` ## Pyomo evaluator ### desdeo.problem.pyomo_evaluator Defines an evaluator compatible with the Problem JSON format and transforms it into a Pyomo model. #### PyomoEvaluator Defines an evaluator that transforms an instance of Problem into a pyomo model. Source code in `desdeo/problem/pyomo_evaluator.py` ``` class PyomoEvaluator: """Defines an evaluator that transforms an instance of Problem into a pyomo model.""" def __init__(self, problem: Problem): """Initializes the evaluator. Args: problem (Problem): the problem to be transformed in a pyomo model. """ model = pyomo.ConcreteModel() # set the parser self.parse = MathParser(to_format=FormatEnum.pyomo).parse # Add variables model = self.init_variables(problem, model) # Add constants, if any if problem.constants is not None: model = self.init_constants(problem, model) # Add extra expressions, if any if problem.extra_funcs is not None: model = self.init_extras(problem, model) # Add objective function expressions model = self.init_objectives(problem, model) # Add scalarization functions, if any if problem.scalarization_funcs is not None: model = self.init_scalarizations(problem, model) # Add constraints, if any if problem.constraints is not None: model = self.init_constraints(problem, model) self.model = model self.problem = problem @classmethod def _bounds_rule(cls, lowerbounds, upperbounds): def bounds_rule(model, *args) -> tuple: indices = tuple(arg - 1 for arg in args) lower_value = lowerbounds upper_value = upperbounds for index in indices: lower_value = lower_value[index] upper_value = upper_value[index] return (lower_value, upper_value) return bounds_rule @classmethod def _init_rule(cls, initial_values): def init_rule(model, *args): indices = tuple(arg - 1 for arg in args) initial_value = initial_values for index in indices: initial_value = initial_value[index] return initial_value return init_rule def init_variables(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: # noqa: C901 """Add variables to the pyomo model. Args: problem (Problem): problem from which to extract the variables. model (pyomo.Model): the pyomo model to add the variables to. Raises: PyomoEvaluator: when a problem in extracting the variables is encountered. I.e., the bounds of the variables are incorrect or of a non supported type. Returns: pyomo.Model: the pyomo model with the variables added as attributes. """ for var in problem.variables: if isinstance(var, Variable): # handle regular variables lowerbound = var.lowerbound if var.lowerbound is not None else float("-inf") upperbound = var.upperbound if var.upperbound is not None else float("inf") # figure out the variable type match (lowerbound >= 0, upperbound >= 0, var.variable_type): case (True, True, VariableTypeEnum.integer): # variable is positive integer domain = pyomo.NonNegativeIntegers case (False, False, VariableTypeEnum.integer): # variable is negative integer domain = pyomo.NegativeIntegers case (False, True, VariableTypeEnum.integer): # variable can be both negative an positive integer domain = pyomo.Integers case (True, False, VariableTypeEnum.integer): # error! lower bound is greater than upper bound msg = ( f"The lower bound {var.lowerbound} for variable {var.symbol} is greater than the " f"upper bound {var.upperbound}" ) raise PyomoEvaluatorError(msg) case (True, True, VariableTypeEnum.real): # variable is positive real domain = pyomo.NonNegativeReals case (False, False, VariableTypeEnum.real): # variable is negative real domain = pyomo.NegativeReals case (False, True, VariableTypeEnum.real): # variable can be both negative and positive real domain = pyomo.Reals case (True, False, VariableTypeEnum.real): # error! lower bound is greater than upper bound msg = ( f"The lower bound {var.lowerbound} for variable {var.symbol} is greater than the " f"upper bound {var.upperbound}" ) raise PyomoEvaluatorError(msg) case (_, _, VariableTypeEnum.binary): domain = pyomo.Binary case _: msg = f"Could not figure out the type for variable {var}." raise PyomoEvaluatorError(msg) # if a variable's initial value is set, use it. Otherwise, check if the lower and upper bounds # are defined, if they are, use the mid-point of the bounds, otherwise use the initial value, which is # None. if var.initial_value is not None: initial_value = var.initial_value else: initial_value = ( var.initial_value if var.lowerbound is None or var.upperbound is None else (var.lowerbound + var.upperbound) / 2 ) pyomo_var = pyomo.Var( name=var.name, initialize=initial_value, bounds=(var.lowerbound, var.upperbound), domain=domain, ) elif isinstance(var, TensorVariable): # handle tensor variables, i.e., vectors etc.. # create the needed range sets index_sets = [pyomo.RangeSet(1, dim_size) for dim_size in var.shape] # TODO: check domain properly if var.variable_type == VariableTypeEnum.binary: domain = pyomo.Binary elif var.variable_type == VariableTypeEnum.integer: domain = pyomo.Integers else: domain = pyomo.Reals # create the Var pyomo_var = pyomo.Var( *index_sets, name=var.name, initialize=self._init_rule(var.get_initial_values()), bounds=self._bounds_rule(var.get_lowerbound_values(), var.get_upperbound_values()), domain=domain, ) else: msg = f"Unsupported variable type '{type(var)} encountered." raise PyomoEvaluatorError(msg) # add and then construct the variable setattr(model, var.symbol, pyomo_var) getattr(model, var.symbol).construct() return model def init_constants(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add constants to a pyomo model. Args: problem (Problem): problem from which to extract the constants. model (pyomo.Model): the pyomo model to add the constants to. Raises: PyomoEvaluatorError: when the domain of a constant cannot be figured out. Returns: pyomo.Model: the pyomo model with the constants added as attributes. """ for con in problem.constants: # Handle regular constnants if isinstance(con, Constant): # figure out the domain of the constant match ( isinstance(con.value, int), isinstance(con.value, float), con.value >= 0, ): case (True, False, True): # positive integer domain = pyomo.NonNegativeIntegers case (True, False, False): # negative integer domain = pyomo.NegativeIntegers case (False, True, True): # positive real domain = pyomo.NonNegativeReals case (False, True, False): # negative real domain = pyomo.NegativeReals case _: # not possible, something went wrong msg = f"Failed to figure out the domain for the constant {con.symbol}." raise PyomoEvaluatorError(msg) pyomo_param = pyomo.Param(name=con.name, default=con.value, domain=domain) elif isinstance(con, TensorConstant): # handle TensorConstants, like vectors # create the needed range sets index_sets = [pyomo.RangeSet(1, dim_size) for dim_size in con.shape] # TODO: check domain properly # for now, constants are always assumed to be real (which is quite safe to do...) domain = pyomo.Reals # create the Con pyomo_param = pyomo.Param( *index_sets, name=con.name, initialize=self._init_rule(con.get_values()), domain=domain, ) else: msg = f"Unsupported constant type '{type(con)}' encountered." raise PyomoEvaluatorError(msg) setattr(model, con.symbol, pyomo_param) return model def init_extras(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add extra function expressions to a pyomo model. Args: problem (Problem): problem from which the extract the extra function expressions. model (pyomo.Model): the pyomo model to add the extra function expressions to. Returns: pyomo.Model: the pyomo model with the expressions added as attributes. """ for extra in problem.extra_funcs: pyomo_expr = self.parse(extra.func, model) setattr(model, extra.symbol, pyomo.Expression(expr=pyomo_expr)) return model def init_objectives(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add objective function expressions to a pyomo model. Does not yet add any actual pyomo objectives, only the expressions of the objectives. A pyomo solved must add the appropiate pyomo objective before solving. Args: problem (Problem): problem from which to extract the objective function expresions. model (pyomo.Model): the pyomo model to add the expressions to. Returns: pyomo.Model: the pyomo model with the objective expressions added as pyomo Objectives. The objectives are deactivated by default. """ for obj in problem.objectives: pyomo_expr = self.parse(obj.func, model) setattr(model, obj.symbol, pyomo.Expression(expr=pyomo_expr)) # the obj.symbol_min objectives are used when optimizing and building scalarizations etc... new_expr = (-1) * pyomo_expr if obj.maximize else pyomo_expr setattr(model, f"{obj.symbol}_min", pyomo.Expression(expr=new_expr)) return model def init_constraints(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add constraint expressions to a pyomo model. Args: problem (Problem): the problem from which to extract the constraint function expressions. model (pyomo.Model): the pyomo model to add the exprssions to. Raises: PyomoEvaluatorError: when an unsupported constraint type is encountered. Returns: pyomo.Model: the pyomo model with the constraint expressions added as pyomo Constraints. """ for cons in problem.constraints: pyomo_expr = self.parse(cons.func, model) match con_type := cons.cons_type: case ConstraintTypeEnum.LTE: # constraints in DESDEO are defined such that they must be less than zero pyomo_expr = _le(pyomo_expr, 0, cons.name) case ConstraintTypeEnum.EQ: if hasattr(pyomo_expr, "is_indexed") and pyomo_expr.is_indexed(): _e = pyomo_expr data = {k: _e[k] == 0 for k in _e.index_set()} pyomo_expr = pyomo.Constraint(_e.index_set(), rule=data) else: pyomo_expr = pyomo.Constraint(expr=pyomo_expr == 0, name=cons.name) pyomo_expr.construct() case _: msg = f"Constraint type of {con_type} not supported. Must be one of {ConstraintTypeEnum}." raise PyomoEvaluatorError(msg) # cons_expr = pyomo.Constraint(expr=pyomo_expr, name=cons.name) setattr(model, cons.symbol, pyomo_expr) # getattr(model, cons.symbol).construct() return model def init_scalarizations(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add scalrization expressions to a pyomo model. Args: problem (Problem): the problem from which to extract thescalarization function expressions. model (pyomo.Model): the pyomo model to add the expressions to. Returns: pyomo.Model: the pyomo model with the scalarization expressions addedd as pyomo Objectives. The objectives are deactivated by default. Scalarization functions are always minimized. """ for scal in problem.scalarization_funcs: pyomo_expr = self.parse(scal.func, model) setattr(model, scal.symbol, pyomo.Expression(expr=pyomo_expr)) return model def evaluate( self, xs: dict[str, float | int | bool | Iterable[float | int | bool]] ) -> dict[str, float | int | bool | list[dict[str, float | int | bool]]]: """Evaluate the current pyomo model with the given decision variable values. Warning: This should not be used for actually solving the pyomo model! For debugging mostly. Args: xs (dict[str, float | int | bool | Iterable[float | int | bool]]): a dict with the decision variable symbols as the keys followed by the corresponding decision variable values, which can also be represented by a list for multiple values. The symbols must match the symbols defined for the decision variables defined in the `Problem` being solved. Each list in the dict should contain the same number of values. Returns: dict | list[dict]: the results of evaluating the pyomo model with its variable values set to the values found in xs. """ res = [] n_samples = len(next(iter(xs.values()))) if isinstance(next(iter(xs.values())), list) else 1 for i in range(n_samples): for var in self.problem.variables: x = xs[var.symbol][i] if isinstance(var, Variable): # scalar variable setattr(self.model, var.symbol, x) else: # tensor variable indices = itertools.product(*[range(1, dim + 1) for dim in var.shape]) # 1-based indexing for idx in indices: elem = x for j in idx: elem = elem[j - 1] # 0-based indexing getattr(self.model, var.symbol)[idx] = elem # 1-based indexing res.append(self.get_values()) return res if len(res) > 1 else res[0] def get_values(self) -> dict[str, float | int | bool]: # noqa: C901 """Get the values from the pyomo model in dict. The keys of the dict will be the symbols defined in the problem utilized to initialize the evaluator. Returns: dict[str, float | int | bool]: a dict with keys equivalent to the symbols defined in self.problem. """ result_dict = {} for var in self.problem.variables: if isinstance(var, Variable): result_dict[var.symbol] = pyomo.value(getattr(self.model, var.symbol)) elif isinstance(var, TensorVariable): result_dict[var.symbol] = getattr(self.model, var.symbol).get_values() else: msg = f"Unsupported variable type {type(var)} encountered." raise PyomoEvaluatorError(msg) for obj in self.problem.objectives: result_dict[obj.symbol] = pyomo.value(getattr(self.model, obj.symbol)) if self.problem.constants is not None: for con in self.problem.constants: if isinstance(con, Constant): result_dict[con.symbol] = pyomo.value(getattr(self.model, con.symbol)) elif isinstance(con, TensorConstant): result_dict[con.symbol] = getattr(self.model, con.symbol).extract_values() else: msg = f"Unsupported variable type {type(var)} encountered." raise PyomoEvaluatorError(msg) if self.problem.extra_funcs is not None: for extra in self.problem.extra_funcs: result_dict[extra.symbol] = pyomo.value(getattr(self.model, extra.symbol)) # TODO: after implementing TensorConstraint, fix this if self.problem.constraints is not None: for const in self.problem.constraints: obj = getattr(self.model, const.symbol) if obj.is_indexed(): result_dict[const.symbol] = {k: pyomo.value(obj[k]) for k in obj} else: result_dict[const.symbol] = pyomo.value(obj) if self.problem.scalarization_funcs is not None: for scal in self.problem.scalarization_funcs: result_dict[scal.symbol] = pyomo.value(getattr(self.model, scal.symbol)) return result_dict def set_optimization_target(self, target: str): """Creates a minimization objective from the target attribute of the pyomo model. The attribute name of the pyomo objective will be target + _objective, e.g., 'f_1' will become 'f_1_objective'. This is done so that the original f_1 expressions attribute does not get reassigned. Args: target (str): an str representing a symbol. Raises: PyomoEvaluatorError: the given target was not an attribute of the pyomo model. """ if not hasattr(self.model, target): msg = f"The pyomo model has no attribute {target}." raise PyomoEvaluatorError(msg) # delete any existing objectives, if any for obj in self.model.component_objects(pyomo.Objective, active=True): obj.deactivate() obj_expr = getattr(self.model, target) objective = pyomo.Objective(expr=obj_expr, sense=pyomo.minimize, name=target) # add the postfix '_objective' to the attribute name of the pyomo objective setattr(self.model, f"{target}_objective", objective) ``` ##### __init__ ``` __init__(problem: Problem) ``` Initializes the evaluator. Parameters: | Name | Type | Description | Default | | --------- | --------- | ----------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to be transformed in a pyomo model. | *required* | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def __init__(self, problem: Problem): """Initializes the evaluator. Args: problem (Problem): the problem to be transformed in a pyomo model. """ model = pyomo.ConcreteModel() # set the parser self.parse = MathParser(to_format=FormatEnum.pyomo).parse # Add variables model = self.init_variables(problem, model) # Add constants, if any if problem.constants is not None: model = self.init_constants(problem, model) # Add extra expressions, if any if problem.extra_funcs is not None: model = self.init_extras(problem, model) # Add objective function expressions model = self.init_objectives(problem, model) # Add scalarization functions, if any if problem.scalarization_funcs is not None: model = self.init_scalarizations(problem, model) # Add constraints, if any if problem.constraints is not None: model = self.init_constraints(problem, model) self.model = model self.problem = problem ``` ##### evaluate ``` evaluate( xs: dict[ str, float | int | bool | Iterable[float | int | bool], ], ) -> dict[ str, float | int | bool | list[dict[str, float | int | bool]], ] ``` Evaluate the current pyomo model with the given decision variable values. Warning This should not be used for actually solving the pyomo model! For debugging mostly. Parameters: | Name | Type | Description | Default | | ---- | ------------------ | ----------- | ------- | | `xs` | \`dict\[str, float | int | bool | Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | int | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def evaluate( self, xs: dict[str, float | int | bool | Iterable[float | int | bool]] ) -> dict[str, float | int | bool | list[dict[str, float | int | bool]]]: """Evaluate the current pyomo model with the given decision variable values. Warning: This should not be used for actually solving the pyomo model! For debugging mostly. Args: xs (dict[str, float | int | bool | Iterable[float | int | bool]]): a dict with the decision variable symbols as the keys followed by the corresponding decision variable values, which can also be represented by a list for multiple values. The symbols must match the symbols defined for the decision variables defined in the `Problem` being solved. Each list in the dict should contain the same number of values. Returns: dict | list[dict]: the results of evaluating the pyomo model with its variable values set to the values found in xs. """ res = [] n_samples = len(next(iter(xs.values()))) if isinstance(next(iter(xs.values())), list) else 1 for i in range(n_samples): for var in self.problem.variables: x = xs[var.symbol][i] if isinstance(var, Variable): # scalar variable setattr(self.model, var.symbol, x) else: # tensor variable indices = itertools.product(*[range(1, dim + 1) for dim in var.shape]) # 1-based indexing for idx in indices: elem = x for j in idx: elem = elem[j - 1] # 0-based indexing getattr(self.model, var.symbol)[idx] = elem # 1-based indexing res.append(self.get_values()) return res if len(res) > 1 else res[0] ``` ##### get_values ``` get_values() -> dict[str, float | int | bool] ``` Get the values from the pyomo model in dict. The keys of the dict will be the symbols defined in the problem utilized to initialize the evaluator. Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | int | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def get_values(self) -> dict[str, float | int | bool]: # noqa: C901 """Get the values from the pyomo model in dict. The keys of the dict will be the symbols defined in the problem utilized to initialize the evaluator. Returns: dict[str, float | int | bool]: a dict with keys equivalent to the symbols defined in self.problem. """ result_dict = {} for var in self.problem.variables: if isinstance(var, Variable): result_dict[var.symbol] = pyomo.value(getattr(self.model, var.symbol)) elif isinstance(var, TensorVariable): result_dict[var.symbol] = getattr(self.model, var.symbol).get_values() else: msg = f"Unsupported variable type {type(var)} encountered." raise PyomoEvaluatorError(msg) for obj in self.problem.objectives: result_dict[obj.symbol] = pyomo.value(getattr(self.model, obj.symbol)) if self.problem.constants is not None: for con in self.problem.constants: if isinstance(con, Constant): result_dict[con.symbol] = pyomo.value(getattr(self.model, con.symbol)) elif isinstance(con, TensorConstant): result_dict[con.symbol] = getattr(self.model, con.symbol).extract_values() else: msg = f"Unsupported variable type {type(var)} encountered." raise PyomoEvaluatorError(msg) if self.problem.extra_funcs is not None: for extra in self.problem.extra_funcs: result_dict[extra.symbol] = pyomo.value(getattr(self.model, extra.symbol)) # TODO: after implementing TensorConstraint, fix this if self.problem.constraints is not None: for const in self.problem.constraints: obj = getattr(self.model, const.symbol) if obj.is_indexed(): result_dict[const.symbol] = {k: pyomo.value(obj[k]) for k in obj} else: result_dict[const.symbol] = pyomo.value(obj) if self.problem.scalarization_funcs is not None: for scal in self.problem.scalarization_funcs: result_dict[scal.symbol] = pyomo.value(getattr(self.model, scal.symbol)) return result_dict ``` ##### init_constants ``` init_constants( problem: Problem, model: Model ) -> pyomo.Model ``` Add constants to a pyomo model. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which to extract the constants. | *required* | | `model` | `Model` | the pyomo model to add the constants to. | *required* | Raises: | Type | Description | | --------------------- | ---------------------------------------------------- | | `PyomoEvaluatorError` | when the domain of a constant cannot be figured out. | Returns: | Type | Description | | ------- | -------------------------------------------------------------------- | | `Model` | pyomo.Model: the pyomo model with the constants added as attributes. | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def init_constants(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add constants to a pyomo model. Args: problem (Problem): problem from which to extract the constants. model (pyomo.Model): the pyomo model to add the constants to. Raises: PyomoEvaluatorError: when the domain of a constant cannot be figured out. Returns: pyomo.Model: the pyomo model with the constants added as attributes. """ for con in problem.constants: # Handle regular constnants if isinstance(con, Constant): # figure out the domain of the constant match ( isinstance(con.value, int), isinstance(con.value, float), con.value >= 0, ): case (True, False, True): # positive integer domain = pyomo.NonNegativeIntegers case (True, False, False): # negative integer domain = pyomo.NegativeIntegers case (False, True, True): # positive real domain = pyomo.NonNegativeReals case (False, True, False): # negative real domain = pyomo.NegativeReals case _: # not possible, something went wrong msg = f"Failed to figure out the domain for the constant {con.symbol}." raise PyomoEvaluatorError(msg) pyomo_param = pyomo.Param(name=con.name, default=con.value, domain=domain) elif isinstance(con, TensorConstant): # handle TensorConstants, like vectors # create the needed range sets index_sets = [pyomo.RangeSet(1, dim_size) for dim_size in con.shape] # TODO: check domain properly # for now, constants are always assumed to be real (which is quite safe to do...) domain = pyomo.Reals # create the Con pyomo_param = pyomo.Param( *index_sets, name=con.name, initialize=self._init_rule(con.get_values()), domain=domain, ) else: msg = f"Unsupported constant type '{type(con)}' encountered." raise PyomoEvaluatorError(msg) setattr(model, con.symbol, pyomo_param) return model ``` ##### init_constraints ``` init_constraints( problem: Problem, model: Model ) -> pyomo.Model ``` Add constraint expressions to a pyomo model. Parameters: | Name | Type | Description | Default | | --------- | --------- | ---------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem from which to extract the constraint function expressions. | *required* | | `model` | `Model` | the pyomo model to add the exprssions to. | *required* | Raises: | Type | Description | | --------------------- | --------------------------------------------------- | | `PyomoEvaluatorError` | when an unsupported constraint type is encountered. | Returns: | Type | Description | | ------- | ---------------------------------------------------------------------------------------- | | `Model` | pyomo.Model: the pyomo model with the constraint expressions added as pyomo Constraints. | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def init_constraints(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add constraint expressions to a pyomo model. Args: problem (Problem): the problem from which to extract the constraint function expressions. model (pyomo.Model): the pyomo model to add the exprssions to. Raises: PyomoEvaluatorError: when an unsupported constraint type is encountered. Returns: pyomo.Model: the pyomo model with the constraint expressions added as pyomo Constraints. """ for cons in problem.constraints: pyomo_expr = self.parse(cons.func, model) match con_type := cons.cons_type: case ConstraintTypeEnum.LTE: # constraints in DESDEO are defined such that they must be less than zero pyomo_expr = _le(pyomo_expr, 0, cons.name) case ConstraintTypeEnum.EQ: if hasattr(pyomo_expr, "is_indexed") and pyomo_expr.is_indexed(): _e = pyomo_expr data = {k: _e[k] == 0 for k in _e.index_set()} pyomo_expr = pyomo.Constraint(_e.index_set(), rule=data) else: pyomo_expr = pyomo.Constraint(expr=pyomo_expr == 0, name=cons.name) pyomo_expr.construct() case _: msg = f"Constraint type of {con_type} not supported. Must be one of {ConstraintTypeEnum}." raise PyomoEvaluatorError(msg) # cons_expr = pyomo.Constraint(expr=pyomo_expr, name=cons.name) setattr(model, cons.symbol, pyomo_expr) # getattr(model, cons.symbol).construct() return model ``` ##### init_extras ``` init_extras(problem: Problem, model: Model) -> pyomo.Model ``` Add extra function expressions to a pyomo model. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which the extract the extra function expressions. | *required* | | `model` | `Model` | the pyomo model to add the extra function expressions to. | *required* | Returns: | Type | Description | | ------- | ---------------------------------------------------------------------- | | `Model` | pyomo.Model: the pyomo model with the expressions added as attributes. | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def init_extras(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add extra function expressions to a pyomo model. Args: problem (Problem): problem from which the extract the extra function expressions. model (pyomo.Model): the pyomo model to add the extra function expressions to. Returns: pyomo.Model: the pyomo model with the expressions added as attributes. """ for extra in problem.extra_funcs: pyomo_expr = self.parse(extra.func, model) setattr(model, extra.symbol, pyomo.Expression(expr=pyomo_expr)) return model ``` ##### init_objectives ``` init_objectives( problem: Problem, model: Model ) -> pyomo.Model ``` Add objective function expressions to a pyomo model. Does not yet add any actual pyomo objectives, only the expressions of the objectives. A pyomo solved must add the appropiate pyomo objective before solving. Parameters: | Name | Type | Description | Default | | --------- | --------- | ---------------------------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which to extract the objective function expresions. | *required* | | `model` | `Model` | the pyomo model to add the expressions to. | *required* | Returns: | Type | Description | | ------- | --------------------------------------------------------------------------------------------------------------------------------- | | `Model` | pyomo.Model: the pyomo model with the objective expressions added as pyomo Objectives. The objectives are deactivated by default. | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def init_objectives(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add objective function expressions to a pyomo model. Does not yet add any actual pyomo objectives, only the expressions of the objectives. A pyomo solved must add the appropiate pyomo objective before solving. Args: problem (Problem): problem from which to extract the objective function expresions. model (pyomo.Model): the pyomo model to add the expressions to. Returns: pyomo.Model: the pyomo model with the objective expressions added as pyomo Objectives. The objectives are deactivated by default. """ for obj in problem.objectives: pyomo_expr = self.parse(obj.func, model) setattr(model, obj.symbol, pyomo.Expression(expr=pyomo_expr)) # the obj.symbol_min objectives are used when optimizing and building scalarizations etc... new_expr = (-1) * pyomo_expr if obj.maximize else pyomo_expr setattr(model, f"{obj.symbol}_min", pyomo.Expression(expr=new_expr)) return model ``` ##### init_scalarizations ``` init_scalarizations( problem: Problem, model: Model ) -> pyomo.Model ``` Add scalrization expressions to a pyomo model. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------------------------------------------------------ | ---------- | | `problem` | `Problem` | the problem from which to extract thescalarization function expressions. | *required* | | `model` | `Model` | the pyomo model to add the expressions to. | *required* | Returns: | Type | Description | | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Model` | pyomo.Model: the pyomo model with the scalarization expressions addedd as pyomo Objectives. The objectives are deactivated by default. Scalarization functions are always minimized. | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def init_scalarizations(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: """Add scalrization expressions to a pyomo model. Args: problem (Problem): the problem from which to extract thescalarization function expressions. model (pyomo.Model): the pyomo model to add the expressions to. Returns: pyomo.Model: the pyomo model with the scalarization expressions addedd as pyomo Objectives. The objectives are deactivated by default. Scalarization functions are always minimized. """ for scal in problem.scalarization_funcs: pyomo_expr = self.parse(scal.func, model) setattr(model, scal.symbol, pyomo.Expression(expr=pyomo_expr)) return model ``` ##### init_variables ``` init_variables( problem: Problem, model: Model ) -> pyomo.Model ``` Add variables to the pyomo model. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which to extract the variables. | *required* | | `model` | `Model` | the pyomo model to add the variables to. | *required* | Raises: | Type | Description | | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `PyomoEvaluator` | when a problem in extracting the variables is encountered. I.e., the bounds of the variables are incorrect or of a non supported type. | Returns: | Type | Description | | ------- | -------------------------------------------------------------------- | | `Model` | pyomo.Model: the pyomo model with the variables added as attributes. | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def init_variables(self, problem: Problem, model: pyomo.Model) -> pyomo.Model: # noqa: C901 """Add variables to the pyomo model. Args: problem (Problem): problem from which to extract the variables. model (pyomo.Model): the pyomo model to add the variables to. Raises: PyomoEvaluator: when a problem in extracting the variables is encountered. I.e., the bounds of the variables are incorrect or of a non supported type. Returns: pyomo.Model: the pyomo model with the variables added as attributes. """ for var in problem.variables: if isinstance(var, Variable): # handle regular variables lowerbound = var.lowerbound if var.lowerbound is not None else float("-inf") upperbound = var.upperbound if var.upperbound is not None else float("inf") # figure out the variable type match (lowerbound >= 0, upperbound >= 0, var.variable_type): case (True, True, VariableTypeEnum.integer): # variable is positive integer domain = pyomo.NonNegativeIntegers case (False, False, VariableTypeEnum.integer): # variable is negative integer domain = pyomo.NegativeIntegers case (False, True, VariableTypeEnum.integer): # variable can be both negative an positive integer domain = pyomo.Integers case (True, False, VariableTypeEnum.integer): # error! lower bound is greater than upper bound msg = ( f"The lower bound {var.lowerbound} for variable {var.symbol} is greater than the " f"upper bound {var.upperbound}" ) raise PyomoEvaluatorError(msg) case (True, True, VariableTypeEnum.real): # variable is positive real domain = pyomo.NonNegativeReals case (False, False, VariableTypeEnum.real): # variable is negative real domain = pyomo.NegativeReals case (False, True, VariableTypeEnum.real): # variable can be both negative and positive real domain = pyomo.Reals case (True, False, VariableTypeEnum.real): # error! lower bound is greater than upper bound msg = ( f"The lower bound {var.lowerbound} for variable {var.symbol} is greater than the " f"upper bound {var.upperbound}" ) raise PyomoEvaluatorError(msg) case (_, _, VariableTypeEnum.binary): domain = pyomo.Binary case _: msg = f"Could not figure out the type for variable {var}." raise PyomoEvaluatorError(msg) # if a variable's initial value is set, use it. Otherwise, check if the lower and upper bounds # are defined, if they are, use the mid-point of the bounds, otherwise use the initial value, which is # None. if var.initial_value is not None: initial_value = var.initial_value else: initial_value = ( var.initial_value if var.lowerbound is None or var.upperbound is None else (var.lowerbound + var.upperbound) / 2 ) pyomo_var = pyomo.Var( name=var.name, initialize=initial_value, bounds=(var.lowerbound, var.upperbound), domain=domain, ) elif isinstance(var, TensorVariable): # handle tensor variables, i.e., vectors etc.. # create the needed range sets index_sets = [pyomo.RangeSet(1, dim_size) for dim_size in var.shape] # TODO: check domain properly if var.variable_type == VariableTypeEnum.binary: domain = pyomo.Binary elif var.variable_type == VariableTypeEnum.integer: domain = pyomo.Integers else: domain = pyomo.Reals # create the Var pyomo_var = pyomo.Var( *index_sets, name=var.name, initialize=self._init_rule(var.get_initial_values()), bounds=self._bounds_rule(var.get_lowerbound_values(), var.get_upperbound_values()), domain=domain, ) else: msg = f"Unsupported variable type '{type(var)} encountered." raise PyomoEvaluatorError(msg) # add and then construct the variable setattr(model, var.symbol, pyomo_var) getattr(model, var.symbol).construct() return model ``` ##### set_optimization_target ``` set_optimization_target(target: str) ``` Creates a minimization objective from the target attribute of the pyomo model. The attribute name of the pyomo objective will be target + \_objective, e.g., 'f_1' will become 'f_1_objective'. This is done so that the original f_1 expressions attribute does not get reassigned. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------- | ---------- | | `target` | `str` | an str representing a symbol. | *required* | Raises: | Type | Description | | --------------------- | --------------------------------------------------------- | | `PyomoEvaluatorError` | the given target was not an attribute of the pyomo model. | Source code in `desdeo/problem/pyomo_evaluator.py` ``` def set_optimization_target(self, target: str): """Creates a minimization objective from the target attribute of the pyomo model. The attribute name of the pyomo objective will be target + _objective, e.g., 'f_1' will become 'f_1_objective'. This is done so that the original f_1 expressions attribute does not get reassigned. Args: target (str): an str representing a symbol. Raises: PyomoEvaluatorError: the given target was not an attribute of the pyomo model. """ if not hasattr(self.model, target): msg = f"The pyomo model has no attribute {target}." raise PyomoEvaluatorError(msg) # delete any existing objectives, if any for obj in self.model.component_objects(pyomo.Objective, active=True): obj.deactivate() obj_expr = getattr(self.model, target) objective = pyomo.Objective(expr=obj_expr, sense=pyomo.minimize, name=target) # add the postfix '_objective' to the attribute name of the pyomo objective setattr(self.model, f"{target}_objective", objective) ``` #### PyomoEvaluatorError Bases: `Exception` Raised when an error within the PyomoEvaluator class is encountered. Source code in `desdeo/problem/pyomo_evaluator.py` ``` class PyomoEvaluatorError(Exception): """Raised when an error within the PyomoEvaluator class is encountered.""" ``` ## Sympy evaluator ### desdeo.problem.sympy_evaluator Implements and evaluator based on sympy expressions. #### SympyEvaluator Defines an evaluator that can be used to evaluate instances of Problem utilizing sympy. Source code in `desdeo/problem/sympy_evaluator.py` ``` class SympyEvaluator: """Defines an evaluator that can be used to evaluate instances of Problem utilizing sympy.""" def __init__(self, problem: Problem): """Initializes the evaluator. Args: problem (Problem): the problem to be evaluated. """ if variable_dimension_enumerate(problem) not in SUPPORTED_VAR_DIMENSIONS: msg = "SymPy evaluator does not yet support tensors." raise SympyEvaluatorError(msg) # Collect all the symbols and expressions in the problem parser = MathParser(to_format=FormatEnum.sympy) self.variable_symbols = [var.symbol for var in problem.variables] self.constant_expressions = ( {const.symbol: parser.parse(const.value) for const in problem.constants} if problem.constants is not None else None ) self.extra_expressions = ( {extra.symbol: parser.parse(extra.func) for extra in problem.extra_funcs} if problem.extra_funcs is not None else None ) self.objective_expressions = {obj.symbol: parser.parse(obj.func) for obj in problem.objectives} self.constraint_expressions = ( {con.symbol: parser.parse(con.func) for con in problem.constraints} if problem.constraints is not None else None ) self.scalarization_expressions = ( {scal.symbol: parser.parse(scal.func) for scal in problem.scalarization_funcs} if problem.scalarization_funcs is not None else None ) # Resolve every kind of expression in the order the other evaluators build them -- # extra functions, objectives, scalarization functions, then constraints. Each kind # may reference the kinds resolved before it, and earlier elements of its own kind. _extra_expressions = _resolve_kind(self.extra_expressions, self.constant_expressions) _objective_expressions = _resolve_kind( self.objective_expressions, self.constant_expressions, _extra_expressions ) # always minimized objective expressions _objective_expressions_min = { f"{obj.symbol}_min": -_objective_expressions[obj.symbol] if obj.maximize else _objective_expressions[obj.symbol] for obj in problem.objectives } _scalarization_expressions = _resolve_kind( self.scalarization_expressions, self.constant_expressions, _extra_expressions, _objective_expressions, _objective_expressions_min, ) # Constraints are resolved last, so that a constraint may reference a scalarization # function. The scenario tools generate exactly that: aggregating a scalarization # with add_worst_case_robust bounds each per-leaf scalarization in a constraint. _constraint_expressions = _resolve_kind( self.constraint_expressions, self.constant_expressions, _extra_expressions, _objective_expressions, _objective_expressions_min, _scalarization_expressions, ) # Every expression must now be in terms of the decision variables alone. A symbol # that survived substitution is a reference that could not be resolved -- typically # to an element declared later. sympy's lambdify would silently close over it and # return an unevaluated expression instead of a number, so reject it here. self._check_fully_substituted( _extra_expressions, _objective_expressions, _objective_expressions_min, _constraint_expressions, _scalarization_expressions, ) # initialize callable lambdas self.lambda_exprs = { _k: _v for _d in [ {k: sp.lambdify(self.variable_symbols, d[k]) for k in d} for d in [ _extra_expressions, _objective_expressions, _objective_expressions_min, _constraint_expressions, _scalarization_expressions, ] if d is not None ] for _k, _v in _d.items() } self.problem = problem self.parser = parser def _check_fully_substituted(self, *expression_maps: "dict | None") -> None: """Verify that no expression refers to anything but the decision variables. Args: *expression_maps: the resolved symbol-to-expression maps to check. Raises: SympyEvaluatorError: if any expression still contains an unresolved symbol. """ known = set(self.variable_symbols) for expressions in expression_maps: for symbol, expr in (expressions or {}).items(): unresolved = sorted(str(s) for s in getattr(expr, "free_symbols", set()) if str(s) not in known) if unresolved: msg = ( f"The expression of '{symbol}' still refers to {unresolved} after substitution. " "Expressions may only reference the decision variables and elements declared " "before them." ) raise SympyEvaluatorError(msg) def evaluate(self, xs: dict[str, float | int | bool]) -> dict[str, float | int | bool]: """Evaluate the the whole problem with a given decision variable dict. Args: xs (dict[str, float | int | bool]): a dict with keys representing decision variable symbols and values with the decision variable value. Returns: dict[str, float | int | bool]: a dict with keys corresponding to each symbol defined for the problem being evaluated and the corresponding expression's value. """ return {k: self.lambda_exprs[k](**xs) for k in self.lambda_exprs} | xs def evaluate_target(self, xs: dict[str, float | int | bool], target: str) -> float: """Evaluates only the specified target with given decision variables. Args: xs (dict[str, float | int | bool]): a dict with keys representing decision variable symbols and values with the decision variable value. target (str): the symbol of the function expressions to be evaluated. Returns: float: the value of the target once evaluated. """ return self.lambda_exprs[target](**xs) def evaluate_constraints(self, xs: dict[str, float | int | bool]) -> dict[str, float | int | bool]: """Evaluates the constraints of the problem with given decision variables. Args: xs (dict[str, float | int | bool]): a dict with keys representing decision variable symbols and values with the decision variable value. Returns: dict[str, float | int | bool]: a dict with keys being the constraints symbols and values being the value of the corresponding constraint. """ return {k: self.lambda_exprs[k](**xs) for k in [constr.symbol for constr in self.problem.constraints]} ``` ##### __init__ ``` __init__(problem: Problem) ``` Initializes the evaluator. Parameters: | Name | Type | Description | Default | | --------- | --------- | ---------------------------- | ---------- | | `problem` | `Problem` | the problem to be evaluated. | *required* | Source code in `desdeo/problem/sympy_evaluator.py` ``` def __init__(self, problem: Problem): """Initializes the evaluator. Args: problem (Problem): the problem to be evaluated. """ if variable_dimension_enumerate(problem) not in SUPPORTED_VAR_DIMENSIONS: msg = "SymPy evaluator does not yet support tensors." raise SympyEvaluatorError(msg) # Collect all the symbols and expressions in the problem parser = MathParser(to_format=FormatEnum.sympy) self.variable_symbols = [var.symbol for var in problem.variables] self.constant_expressions = ( {const.symbol: parser.parse(const.value) for const in problem.constants} if problem.constants is not None else None ) self.extra_expressions = ( {extra.symbol: parser.parse(extra.func) for extra in problem.extra_funcs} if problem.extra_funcs is not None else None ) self.objective_expressions = {obj.symbol: parser.parse(obj.func) for obj in problem.objectives} self.constraint_expressions = ( {con.symbol: parser.parse(con.func) for con in problem.constraints} if problem.constraints is not None else None ) self.scalarization_expressions = ( {scal.symbol: parser.parse(scal.func) for scal in problem.scalarization_funcs} if problem.scalarization_funcs is not None else None ) # Resolve every kind of expression in the order the other evaluators build them -- # extra functions, objectives, scalarization functions, then constraints. Each kind # may reference the kinds resolved before it, and earlier elements of its own kind. _extra_expressions = _resolve_kind(self.extra_expressions, self.constant_expressions) _objective_expressions = _resolve_kind( self.objective_expressions, self.constant_expressions, _extra_expressions ) # always minimized objective expressions _objective_expressions_min = { f"{obj.symbol}_min": -_objective_expressions[obj.symbol] if obj.maximize else _objective_expressions[obj.symbol] for obj in problem.objectives } _scalarization_expressions = _resolve_kind( self.scalarization_expressions, self.constant_expressions, _extra_expressions, _objective_expressions, _objective_expressions_min, ) # Constraints are resolved last, so that a constraint may reference a scalarization # function. The scenario tools generate exactly that: aggregating a scalarization # with add_worst_case_robust bounds each per-leaf scalarization in a constraint. _constraint_expressions = _resolve_kind( self.constraint_expressions, self.constant_expressions, _extra_expressions, _objective_expressions, _objective_expressions_min, _scalarization_expressions, ) # Every expression must now be in terms of the decision variables alone. A symbol # that survived substitution is a reference that could not be resolved -- typically # to an element declared later. sympy's lambdify would silently close over it and # return an unevaluated expression instead of a number, so reject it here. self._check_fully_substituted( _extra_expressions, _objective_expressions, _objective_expressions_min, _constraint_expressions, _scalarization_expressions, ) # initialize callable lambdas self.lambda_exprs = { _k: _v for _d in [ {k: sp.lambdify(self.variable_symbols, d[k]) for k in d} for d in [ _extra_expressions, _objective_expressions, _objective_expressions_min, _constraint_expressions, _scalarization_expressions, ] if d is not None ] for _k, _v in _d.items() } self.problem = problem self.parser = parser ``` ##### \_check_fully_substituted ``` _check_fully_substituted( *expression_maps: dict | None, ) -> None ``` Verify that no expression refers to anything but the decision variables. Parameters: | Name | Type | Description | Default | | ------------------ | ------ | ----------- | ------------------------------------------------ | | `*expression_maps` | \`dict | None\` | the resolved symbol-to-expression maps to check. | Raises: | Type | Description | | --------------------- | ------------------------------------------------------ | | `SympyEvaluatorError` | if any expression still contains an unresolved symbol. | Source code in `desdeo/problem/sympy_evaluator.py` ``` def _check_fully_substituted(self, *expression_maps: "dict | None") -> None: """Verify that no expression refers to anything but the decision variables. Args: *expression_maps: the resolved symbol-to-expression maps to check. Raises: SympyEvaluatorError: if any expression still contains an unresolved symbol. """ known = set(self.variable_symbols) for expressions in expression_maps: for symbol, expr in (expressions or {}).items(): unresolved = sorted(str(s) for s in getattr(expr, "free_symbols", set()) if str(s) not in known) if unresolved: msg = ( f"The expression of '{symbol}' still refers to {unresolved} after substitution. " "Expressions may only reference the decision variables and elements declared " "before them." ) raise SympyEvaluatorError(msg) ``` ##### evaluate ``` evaluate( xs: dict[str, float | int | bool], ) -> dict[str, float | int | bool] ``` Evaluate the the whole problem with a given decision variable dict. Parameters: | Name | Type | Description | Default | | ---- | ------------------ | ----------- | -------- | | `xs` | \`dict\[str, float | int | bool\]\` | Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | int | Source code in `desdeo/problem/sympy_evaluator.py` ``` def evaluate(self, xs: dict[str, float | int | bool]) -> dict[str, float | int | bool]: """Evaluate the the whole problem with a given decision variable dict. Args: xs (dict[str, float | int | bool]): a dict with keys representing decision variable symbols and values with the decision variable value. Returns: dict[str, float | int | bool]: a dict with keys corresponding to each symbol defined for the problem being evaluated and the corresponding expression's value. """ return {k: self.lambda_exprs[k](**xs) for k in self.lambda_exprs} | xs ``` ##### evaluate_constraints ``` evaluate_constraints( xs: dict[str, float | int | bool], ) -> dict[str, float | int | bool] ``` Evaluates the constraints of the problem with given decision variables. Parameters: | Name | Type | Description | Default | | ---- | ------------------ | ----------- | -------- | | `xs` | \`dict\[str, float | int | bool\]\` | Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | int | Source code in `desdeo/problem/sympy_evaluator.py` ``` def evaluate_constraints(self, xs: dict[str, float | int | bool]) -> dict[str, float | int | bool]: """Evaluates the constraints of the problem with given decision variables. Args: xs (dict[str, float | int | bool]): a dict with keys representing decision variable symbols and values with the decision variable value. Returns: dict[str, float | int | bool]: a dict with keys being the constraints symbols and values being the value of the corresponding constraint. """ return {k: self.lambda_exprs[k](**xs) for k in [constr.symbol for constr in self.problem.constraints]} ``` ##### evaluate_target ``` evaluate_target( xs: dict[str, float | int | bool], target: str ) -> float ``` Evaluates only the specified target with given decision variables. Parameters: | Name | Type | Description | Default | | -------- | ------------------ | ------------------------------------------------------- | ---------- | | `xs` | \`dict\[str, float | int | bool\]\` | | `target` | `str` | the symbol of the function expressions to be evaluated. | *required* | Returns: | Name | Type | Description | | ------- | ------- | --------------------------------------- | | `float` | `float` | the value of the target once evaluated. | Source code in `desdeo/problem/sympy_evaluator.py` ``` def evaluate_target(self, xs: dict[str, float | int | bool], target: str) -> float: """Evaluates only the specified target with given decision variables. Args: xs (dict[str, float | int | bool]): a dict with keys representing decision variable symbols and values with the decision variable value. target (str): the symbol of the function expressions to be evaluated. Returns: float: the value of the target once evaluated. """ return self.lambda_exprs[target](**xs) ``` #### SympyEvaluatorError Bases: `Exception` Raised when an exception with a Sympy evaluator is encountered. Source code in `desdeo/problem/sympy_evaluator.py` ``` class SympyEvaluatorError(Exception): """Raised when an exception with a Sympy evaluator is encountered.""" ``` #### \_resolve_kind ``` _resolve_kind( expressions: dict | None, *maps: dict | None ) -> dict | None ``` Substitute *maps* into each expression of one kind of problem element. Elements are resolved in declaration order and each one also has the already resolved elements of its own kind substituted into it. A scalarization function may therefore be defined in terms of one declared before it, as in the other evaluators. Only backward references resolve; a reference to an element declared later stays unsubstituted and is caught when the expressions are checked. Parameters: | Name | Type | Description | Default | | ------------- | ------ | ----------- | ---------------------------------------------------------------- | | `expressions` | \`dict | None\` | symbol-to-expression map for one kind of element, or None. | | `*maps` | \`dict | None\` | substitution maps to apply, in order, before the same-kind pass. | Returns: | Type | Description | | ------ | ----------- | | \`dict | None\` | Source code in `desdeo/problem/sympy_evaluator.py` ``` def _resolve_kind(expressions: "dict | None", *maps: "dict | None") -> "dict | None": """Substitute *maps* into each expression of one kind of problem element. Elements are resolved in declaration order and each one also has the already resolved elements of its own kind substituted into it. A scalarization function may therefore be defined in terms of one declared before it, as in the other evaluators. Only backward references resolve; a reference to an element declared later stays unsubstituted and is caught when the expressions are checked. Args: expressions: symbol-to-expression map for one kind of element, or None. *maps: substitution maps to apply, in order, before the same-kind pass. Returns: A new symbol-to-expression map, or None if *expressions* was None. """ if expressions is None: return None resolved: dict[str, sp.Expr] = {} for symbol, expr in expressions.items(): resolved[symbol] = _substitute(expr, *maps, resolved) return resolved ``` #### \_substitute ``` _substitute(expr: Expr, *maps: dict | None) -> sp.Expr ``` Substitute each of the given symbol-to-expression maps into an expression. Source code in `desdeo/problem/sympy_evaluator.py` ``` def _substitute(expr: sp.Expr, *maps: "dict | None") -> sp.Expr: """Substitute each of the given symbol-to-expression maps into an expression.""" for mapping in maps: if mapping: expr = expr.subs(mapping, evaluate=False) return expr ``` ## Gurobipy evaluator ### desdeo.problem.gurobipy_evaluator Defines an evaluator compatible with the Problem JSON format and transforms it into a GurobipyModel. #### GurobipyEvaluator Defines as evaluator that transforms an instance of Problem into a GurobipyModel. Source code in `desdeo/problem/gurobipy_evaluator.py` ``` class GurobipyEvaluator: """Defines as evaluator that transforms an instance of Problem into a GurobipyModel.""" variables: dict[str, gp.Var | gp.MVar] constraints: dict[str, gp.Constr] objective_functions: dict[str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr] scalarizations: dict[str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr] extra_functions: dict[ str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr | gp.GenExpr | int | float ] constants: dict[str, int | float | list[int] | list[float]] model: gp.Model def __init__(self, problem: Problem): """Initialized the evaluator. Args: problem (Problem): the problem to be transformed in a GurobipyModel. """ self.model = gp.Model(problem.name) self.objective_functions = {} self.scalarizations = {} self.extra_functions = {} self.constants = {} self.variables = {} self.constraints = {} # set the parser self.parse = MathParser(to_format=FormatEnum.gurobipy).parse # Add variables self.variables = self.init_variables(problem) # Add constants, if any if problem.constants is not None: self.constants = self.init_constants(problem) # Add extra expressions, if any if problem.extra_funcs is not None: self.extra_functions = self.init_extras(problem) # Add objective function expressions self.objective_functions = self.init_objectives(problem) # Add scalarization functions, if any if problem.scalarization_funcs is not None: self.scalarizations = self.init_scalarizations(problem) # Add constraints, if any if problem.constraints is not None: self.constraints = self.init_constraints(problem) self.problem = problem def init_variables(self, problem: Problem) -> dict[str, gp.Var | gp.MVar]: """Add variables to the GurobipyModel. Args: problem (Problem): problem from which to extract the variables. Raises: GurobipyEvaluatorError: when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. Returns: dict[str, gp.Var | gp.MVar]: the variables added to the model. """ variables = {} for var in problem.variables: if isinstance(var, Variable): # handle regular variables lowerbound = var.lowerbound if var.lowerbound is not None else float("-inf") upperbound = var.upperbound if var.upperbound is not None else float("inf") # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer domain = gp.GRB.INTEGER case VariableTypeEnum.real: # variable is real domain = gp.GRB.CONTINUOUS case VariableTypeEnum.binary: domain = gp.GRB.BINARY case _: msg = f"Could not figure out the type for variable {var}." raise GurobipyEvaluatorError(msg) # add the variable to the model gvar = self.model.addVar(lb=lowerbound, ub=upperbound, vtype=domain, name=var.symbol) # set the initial value, if one has been defined if var.initial_value is not None: gvar.setAttr("Start", var.initial_value) variables[var.symbol] = gvar elif isinstance(var, TensorVariable): # handle tensor variables, i.e., vectors etc.. lowerbounds = ( var.get_lowerbound_values() if var.lowerbounds is not None else np.full(var.shape, float("-inf")).tolist() ) upperbounds = ( var.get_upperbound_values() if var.upperbounds is not None else np.full(var.shape, float("inf")).tolist() ) # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer domain = gp.GRB.INTEGER case VariableTypeEnum.real: # variable is real domain = gp.GRB.CONTINUOUS case VariableTypeEnum.binary: domain = gp.GRB.BINARY case _: msg = f"Could not figure out the type for variable {var}." raise GurobipyEvaluatorError(msg) # add the variable to the model gvar = self.model.addMVar( shape=tuple(var.shape), lb=np.array(lowerbounds), ub=np.array(upperbounds), vtype=domain, name=var.symbol, ) # set the initial value, if one has been defined if var.initial_values is not None: gvar.setAttr("Start", np.array(var.get_initial_values())) variables[var.symbol] = gvar # update the model before returning, so that other expressions can reference the variables self.model.update() return variables def init_constants(self, problem: Problem) -> dict[str, int | float | list[int] | list[float]]: """Add constants to a GurobipyEvaluator. Gurobi does not really have constants, so this function instead stores them in a dict, that is then stored in the evaluator. This is necessary to get the MathParser to understand the constants used in the problem, but updating them at a later point will not update any expression referencing them. The expressions that have been defined using these constants will keep using the numeric value of the constant at the time when the expression was created. Thus, it might be best to avoid using constants if you are intending to use the gurobipy solver. Args: problem (Problem): problem from which to extract the constants. Raises: GurobipyEvaluatorError: when the domain of a constant cannot be figured out. Returns: dict[str, int | float]: a dict containing the constants. """ constants: dict[str, int | float | list[int] | list[float]] = {} for con in problem.constants: if isinstance(con, Constant): constants[con.symbol] = con.value elif isinstance(con, TensorConstant): constants[con.symbol] = con.get_values() return constants def init_extras( self, problem: Problem ) -> dict[str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr | gp.GenExpr | int | float]: """Add extra function expressions to a Gurobipy Model. Gurobi does not support extra expressions natively, so this function instead stores them in a dict to be used by the evaluator. This is necessary to get the MathParser to understand the extra expressions used in the problem, but updating them at a later point will not update any expression referencing them. The expressions that have been defined using these extra expressions will keep using the value of the extra expression at the time when the expression was created. Thus, it might be best to avoid using extra expressions if you are intending to use the gurobipy solver. Args: problem (Problem): problem from which the extract the extra function expressions. Returns: GurobipyModel: the GurobipyModel with the expressions added as attributes. """ for extra in problem.extra_funcs: self.extra_functions[extra.symbol] = self.parse(extra.func, callback=self.get_expression_by_name) return self.extra_functions def init_objectives( self, problem: Problem ) -> dict[str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr]: """Add objective function expressions to a Gurobipy Model. Does not yet add any actual gurobipy optimization objectives, only creates a dict containing the expressions of the objectives. The objective expressions are stored in the evaluator and appropiate gurobipy objective must be added to the model before solving. Args: problem (Problem): problem from which to extract the objective function expresions. Returns: dict: dict containing the objective functions. """ for obj in problem.objectives: self.add_objective(obj) return self.objective_functions def init_constraints(self, problem: Problem, model: gp.Model | None = None) -> dict[str, gp.Constr]: """Add constraint expressions to a Gurobipy Model. Args: problem (Problem): the problem from which to extract the constraint function expressions. model (GurobipyModel | None): the GurobipyModel to add the expressions to. Raises: GurobipyEvaluatorError: when an unsupported constraint type is encountered. Returns: dict: the dict with the constraint expressions added to the model. """ for cons in problem.constraints: gp_expr = self.parse(cons.func, callback=self.get_expression_by_name) match con_type := cons.cons_type: case ConstraintTypeEnum.LTE: # constraints in DESDEO are defined such that they must be less than zero gp_expr = _le(gp_expr, 0) case ConstraintTypeEnum.EQ: gp_expr = _eq(gp_expr, 0) case _: msg = f"Constraint type of {con_type} not supported. Must be one of {ConstraintTypeEnum}." raise GurobipyEvaluatorError(msg) self.constraints[cons.symbol] = self.model.addConstr(gp_expr, name=cons.symbol) self.model.update() return self.constraints def init_scalarizations( self, problem: Problem ) -> dict[str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr]: """Add scalrization expressions to a gurobipy model. Scalarizations work identically to objectives, except they are stored in a different dict in the GurobipyModel. If you want to solve the problem using a scalarization, the evaluator needs to set it as an optimization target first. Args: problem (Problem): the problem from which to extract the scalarization function expressions. Returns: dict: the dict with the scalarization expressions. Scalarization functions are always minimized. """ for scal in problem.scalarization_funcs: self.add_scalarization_function(scal) return self.scalarizations def add_constraint(self, constraint: Constraint) -> gp.Constr: """Add a constraint expression to a GurobipyModel. If adding a lot of constraints, this function may end up being very slow compared to adding the constraints to the stored model directly, because of the model.update() calls. Args: constraint (Constraint): the constraint function expression. Raises: GurobipyEvaluatorError: when an unsupported constraint type is encountered. Returns: gurobipy.Constr: The gurobipy constraint that was added. """ gp_expr = self.parse(constraint.func, self.get_expression_by_name) match con_type := constraint.cons_type: case ConstraintTypeEnum.LTE: # constraints in DESDEO are defined such that they must be less than zero gp_expr = _le(gp_expr, 0) case ConstraintTypeEnum.EQ: gp_expr = _eq(gp_expr, 0) case _: msg = f"Constraint type of {con_type} not supported. Must be one of {ConstraintTypeEnum}." raise GurobipyEvaluatorError(msg) return_cons = self.model.addConstr(gp_expr, name=constraint.symbol) self.model.update() self.constraints[constraint.symbol] = return_cons return return_cons def add_objective(self, obj: Objective): """Adds an objective function expression to a GurobipyModel. Does not yet add any actual gurobipy optimization objectives, only adds them to the dict containing the expressions of the objectives. The objective expressions are stored in the GurobipyModel and the evaluator must add the appropiate gurobipy objective before solving. Args: obj (Objective): the objective function expression to be added. """ gp_expr = self.parse(obj.func, self.get_expression_by_name) if isinstance(gp_expr, int | float): warnings.warn( "One or more of the problem objectives seems to be a constant.", GurobipyEvaluatorWarning, stacklevel=2 ) if isinstance(gp_expr, gp.GenExpr): msg = f"Gurobi does not support objective functions that are not linear or quadratic {gp_expr}" raise GurobipyEvaluatorError(msg) self.objective_functions[obj.symbol] = gp_expr # the obj.symbol_min objectives are used when optimizing and building scalarizations etc... self.objective_functions[f"{obj.symbol}_min"] = -gp_expr if obj.maximize else gp_expr def add_scalarization_function(self, scal: ScalarizationFunction): """Adds a scalrization expression to a gurobipy model. Scalarizations work identically to objectives, except they are stored in a different dict in the GurobipyModel. If you want to solve the problem using a scalarization, the evaluator needs to set it as an optimization target first. Args: scal (ScalarizationFunction): The scalarization function to be added. """ self.scalarizations[scal.symbol] = self.parse(scal.func, self.get_expression_by_name) def add_variable(self, var: Variable | TensorVariable) -> gp.Var | gp.MVar: """Add variables to the GurobipyModel. If adding a lot of variables, this function may end up being very slow compared to adding the variables to the stored model directly, because of the model.update() calls. Args: var (Variable): The definition of the variable to be added. Raises: GurobipyEvaluatorError: when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. Returns: gp.Var: the variable that was added to the model. """ if isinstance(var, Variable): # handle regular variables lowerbound = var.lowerbound if var.lowerbound is not None else float("-inf") upperbound = var.upperbound if var.upperbound is not None else float("inf") # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer domain = gp.GRB.INTEGER case VariableTypeEnum.real: # variable is real domain = gp.GRB.CONTINUOUS case VariableTypeEnum.binary: domain = gp.GRB.BINARY case _: msg = f"Could not figure out the type for variable {var}." raise GurobipyEvaluatorError(msg) # add the variable to the model gvar = self.model.addVar(lb=lowerbound, ub=upperbound, vtype=domain, name=var.symbol) # set the initial value, if one has been defined if var.initial_value is not None: gvar.setAttr("Start", var.initial_value) elif isinstance(var, TensorVariable): # handle tensor variables, i.e., vectors etc.. lowerbounds = ( var.get_lowerbound_values() if var.lowerbounds is not None else np.full(var.shape, float("-inf")).tolist() ) upperbounds = ( var.get_upperbound_values() if var.upperbounds is not None else np.full(var.shape, float("inf")).tolist() ) # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer domain = gp.GRB.INTEGER case VariableTypeEnum.real: # variable is real domain = gp.GRB.CONTINUOUS case VariableTypeEnum.binary: domain = gp.GRB.BINARY case _: msg = f"Could not figure out the type for variable {var}." raise GurobipyEvaluatorError(msg) # add the variable to the model gvar = self.model.addMVar( shape=tuple(var.shape), lb=np.array(lowerbounds), ub=np.array(upperbounds), vtype=domain, name=var.symbol, ) # set the initial value, if one has been defined if var.initial_values is not None: gvar.setAttr("Start", np.array(var.get_initial_values())) self.model.update() self.variables[var.symbol] = gvar return gvar def get_expression_by_name( self, name: str ) -> ( gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr | gp.GenExpr | int | float | np.ndarray ): """Returns a gurobipy expression corresponding to the name. Only looks for variables, objective functions, scalarizations, extra functions, and constants. This will not find constraints. Args: name (str): The symbol of the expression. Returns: gurobipy expression: A mathematical expression that gp.Model can use either as a constraint or an objective """ if name in self.variables: expression = self.variables[name] elif name in self.objective_functions: expression = self.objective_functions[name] elif name in self.scalarizations: expression = self.scalarizations[name] elif name in self.extra_functions: expression = self.extra_functions[name] elif name in self.constants: if isinstance(self.constants[name], list): expression = np.array(self.constants[name]) else: expression = self.constants[name] else: msg = f"No expression with name {name} found in the gurobipy model." raise GurobipyEvaluatorError(msg) return expression def get_values(self) -> dict[str, float | int | bool | list[float] | list[int]]: """Get the values from the Gurobipy Model in a dict. The keys of the dict will be the symbols defined in the problem utilized to initialize the evaluator. Returns: dict[str, float | int | bool]: a dict with keys equivalent to the symbols defined in self.problem. """ result_dict = {} for var in self.problem.variables: result_dict[var.symbol] = self.variables[var.symbol].getAttr(gp.GRB.Attr.X) for obj in self.problem.objectives: result_dict[obj.symbol] = self.objective_functions[obj.symbol].getValue() if self.problem.constants is not None: for con in self.problem.constants: result_dict[con.symbol] = self.constants[con.symbol] if self.problem.extra_funcs is not None: for extra in self.problem.extra_funcs: result_dict[extra.symbol] = self.extra_functions[extra.symbol].getValue() if self.problem.constraints is not None: for const in self.problem.constraints: con = self.constraints[const.symbol] if isinstance(con, gp.MQConstr): slack = con.QCSlack result_dict[const.symbol] = (-np.array(slack)).tolist() if hasattr(slack, "__len__") else -slack elif isinstance(con, gp.MConstr): result_dict[const.symbol] = (-con.Slack).tolist() elif isinstance(con, gp.QConstr): result_dict[const.symbol] = -con.getAttr("QCSlack") else: result_dict[const.symbol] = -con.getAttr("Slack") if self.problem.scalarization_funcs is not None: for scal in self.problem.scalarization_funcs: result_dict[scal.symbol] = self.scalarizations[scal.symbol].getValue() return result_dict def remove_constraint(self, symbol: str): """Removes a constraint from the model. If removing a lot of constraints or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the stored model directly may be faster. Args: symbol (str): a str representing the symbol of the constraint to be removed. """ self.model.remove(self.constraints[symbol]) self.constraints.pop(symbol) self.model.update() def remove_variable(self, symbol: str): """Removes a variable from the model. If removing a lot of variables or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the stored model directly may be faster. Args: symbol (str): a str representing the symbol of the variable to be removed. """ self.model.remove(self.variables[symbol]) self.variables.pop(symbol) self.model.update() def set_optimization_target(self, target: str, maximize: bool = False): """Sets a minimization objective to match the target objective or scalarization of the gurobipy model. Args: target (str): an str representing a symbol. Needs to match an objective function or scalarization function already found in the model. maximize (bool): If true, the target function is maximized instead of minimized Raises: GurobipyEvaluatorError: the given target was not an attribute of the gurobipy model. """ if target in self.objective_functions: objective = self.problem.get_objective(symbol=target, copy=False) maximize = False if objective is None else bool(objective.maximize) elif target in self.scalarizations: maximize = False else: msg = f"The gurobipy model has no objective or scalarization named {target}." raise GurobipyEvaluatorError(msg) obj_expr = self.get_expression_by_name(target) if maximize: self.model.setObjective(obj_expr, sense=gp.GRB.MAXIMIZE) else: self.model.setObjective(obj_expr) ``` ##### __init__ ``` __init__(problem: Problem) ``` Initialized the evaluator. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to be transformed in a GurobipyModel. | *required* | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def __init__(self, problem: Problem): """Initialized the evaluator. Args: problem (Problem): the problem to be transformed in a GurobipyModel. """ self.model = gp.Model(problem.name) self.objective_functions = {} self.scalarizations = {} self.extra_functions = {} self.constants = {} self.variables = {} self.constraints = {} # set the parser self.parse = MathParser(to_format=FormatEnum.gurobipy).parse # Add variables self.variables = self.init_variables(problem) # Add constants, if any if problem.constants is not None: self.constants = self.init_constants(problem) # Add extra expressions, if any if problem.extra_funcs is not None: self.extra_functions = self.init_extras(problem) # Add objective function expressions self.objective_functions = self.init_objectives(problem) # Add scalarization functions, if any if problem.scalarization_funcs is not None: self.scalarizations = self.init_scalarizations(problem) # Add constraints, if any if problem.constraints is not None: self.constraints = self.init_constraints(problem) self.problem = problem ``` ##### add_constraint ``` add_constraint(constraint: Constraint) -> gp.Constr ``` Add a constraint expression to a GurobipyModel. If adding a lot of constraints, this function may end up being very slow compared to adding the constraints to the stored model directly, because of the model.update() calls. Parameters: | Name | Type | Description | Default | | ------------ | ------------ | ----------------------------------- | ---------- | | `constraint` | `Constraint` | the constraint function expression. | *required* | Raises: | Type | Description | | ------------------------ | --------------------------------------------------- | | `GurobipyEvaluatorError` | when an unsupported constraint type is encountered. | Returns: | Type | Description | | -------- | -------------------------------------------------------- | | `Constr` | gurobipy.Constr: The gurobipy constraint that was added. | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def add_constraint(self, constraint: Constraint) -> gp.Constr: """Add a constraint expression to a GurobipyModel. If adding a lot of constraints, this function may end up being very slow compared to adding the constraints to the stored model directly, because of the model.update() calls. Args: constraint (Constraint): the constraint function expression. Raises: GurobipyEvaluatorError: when an unsupported constraint type is encountered. Returns: gurobipy.Constr: The gurobipy constraint that was added. """ gp_expr = self.parse(constraint.func, self.get_expression_by_name) match con_type := constraint.cons_type: case ConstraintTypeEnum.LTE: # constraints in DESDEO are defined such that they must be less than zero gp_expr = _le(gp_expr, 0) case ConstraintTypeEnum.EQ: gp_expr = _eq(gp_expr, 0) case _: msg = f"Constraint type of {con_type} not supported. Must be one of {ConstraintTypeEnum}." raise GurobipyEvaluatorError(msg) return_cons = self.model.addConstr(gp_expr, name=constraint.symbol) self.model.update() self.constraints[constraint.symbol] = return_cons return return_cons ``` ##### add_objective ``` add_objective(obj: Objective) ``` Adds an objective function expression to a GurobipyModel. Does not yet add any actual gurobipy optimization objectives, only adds them to the dict containing the expressions of the objectives. The objective expressions are stored in the GurobipyModel and the evaluator must add the appropiate gurobipy objective before solving. Parameters: | Name | Type | Description | Default | | ----- | ----------- | ---------------------------------------------- | ---------- | | `obj` | `Objective` | the objective function expression to be added. | *required* | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def add_objective(self, obj: Objective): """Adds an objective function expression to a GurobipyModel. Does not yet add any actual gurobipy optimization objectives, only adds them to the dict containing the expressions of the objectives. The objective expressions are stored in the GurobipyModel and the evaluator must add the appropiate gurobipy objective before solving. Args: obj (Objective): the objective function expression to be added. """ gp_expr = self.parse(obj.func, self.get_expression_by_name) if isinstance(gp_expr, int | float): warnings.warn( "One or more of the problem objectives seems to be a constant.", GurobipyEvaluatorWarning, stacklevel=2 ) if isinstance(gp_expr, gp.GenExpr): msg = f"Gurobi does not support objective functions that are not linear or quadratic {gp_expr}" raise GurobipyEvaluatorError(msg) self.objective_functions[obj.symbol] = gp_expr # the obj.symbol_min objectives are used when optimizing and building scalarizations etc... self.objective_functions[f"{obj.symbol}_min"] = -gp_expr if obj.maximize else gp_expr ``` ##### add_scalarization_function ``` add_scalarization_function(scal: ScalarizationFunction) ``` Adds a scalrization expression to a gurobipy model. Scalarizations work identically to objectives, except they are stored in a different dict in the GurobipyModel. If you want to solve the problem using a scalarization, the evaluator needs to set it as an optimization target first. Parameters: | Name | Type | Description | Default | | ------ | ----------------------- | --------------------------------------- | ---------- | | `scal` | `ScalarizationFunction` | The scalarization function to be added. | *required* | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def add_scalarization_function(self, scal: ScalarizationFunction): """Adds a scalrization expression to a gurobipy model. Scalarizations work identically to objectives, except they are stored in a different dict in the GurobipyModel. If you want to solve the problem using a scalarization, the evaluator needs to set it as an optimization target first. Args: scal (ScalarizationFunction): The scalarization function to be added. """ self.scalarizations[scal.symbol] = self.parse(scal.func, self.get_expression_by_name) ``` ##### add_variable ``` add_variable( var: Variable | TensorVariable, ) -> gp.Var | gp.MVar ``` Add variables to the GurobipyModel. If adding a lot of variables, this function may end up being very slow compared to adding the variables to the stored model directly, because of the model.update() calls. Parameters: | Name | Type | Description | Default | | ----- | ---------- | ------------------------------------------- | ---------- | | `var` | `Variable` | The definition of the variable to be added. | *required* | Raises: | Type | Description | | ------------------------ | ----------------------------------------------------------------------------------------------------------- | | `GurobipyEvaluatorError` | when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. | Returns: | Type | Description | | ----- | ----------- | | \`Var | MVar\` | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def add_variable(self, var: Variable | TensorVariable) -> gp.Var | gp.MVar: """Add variables to the GurobipyModel. If adding a lot of variables, this function may end up being very slow compared to adding the variables to the stored model directly, because of the model.update() calls. Args: var (Variable): The definition of the variable to be added. Raises: GurobipyEvaluatorError: when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. Returns: gp.Var: the variable that was added to the model. """ if isinstance(var, Variable): # handle regular variables lowerbound = var.lowerbound if var.lowerbound is not None else float("-inf") upperbound = var.upperbound if var.upperbound is not None else float("inf") # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer domain = gp.GRB.INTEGER case VariableTypeEnum.real: # variable is real domain = gp.GRB.CONTINUOUS case VariableTypeEnum.binary: domain = gp.GRB.BINARY case _: msg = f"Could not figure out the type for variable {var}." raise GurobipyEvaluatorError(msg) # add the variable to the model gvar = self.model.addVar(lb=lowerbound, ub=upperbound, vtype=domain, name=var.symbol) # set the initial value, if one has been defined if var.initial_value is not None: gvar.setAttr("Start", var.initial_value) elif isinstance(var, TensorVariable): # handle tensor variables, i.e., vectors etc.. lowerbounds = ( var.get_lowerbound_values() if var.lowerbounds is not None else np.full(var.shape, float("-inf")).tolist() ) upperbounds = ( var.get_upperbound_values() if var.upperbounds is not None else np.full(var.shape, float("inf")).tolist() ) # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer domain = gp.GRB.INTEGER case VariableTypeEnum.real: # variable is real domain = gp.GRB.CONTINUOUS case VariableTypeEnum.binary: domain = gp.GRB.BINARY case _: msg = f"Could not figure out the type for variable {var}." raise GurobipyEvaluatorError(msg) # add the variable to the model gvar = self.model.addMVar( shape=tuple(var.shape), lb=np.array(lowerbounds), ub=np.array(upperbounds), vtype=domain, name=var.symbol, ) # set the initial value, if one has been defined if var.initial_values is not None: gvar.setAttr("Start", np.array(var.get_initial_values())) self.model.update() self.variables[var.symbol] = gvar return gvar ``` ##### get_expression_by_name ``` get_expression_by_name( name: str, ) -> ( gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr | gp.GenExpr | int | float | np.ndarray ) ``` Returns a gurobipy expression corresponding to the name. Only looks for variables, objective functions, scalarizations, extra functions, and constants. This will not find constraints. Parameters: | Name | Type | Description | Default | | ------ | ----- | ----------------------------- | ---------- | | `name` | `str` | The symbol of the expression. | *required* | Returns: | Type | Description | | ----- | ----------- | | \`Var | MVar | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def get_expression_by_name( self, name: str ) -> ( gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr | gp.GenExpr | int | float | np.ndarray ): """Returns a gurobipy expression corresponding to the name. Only looks for variables, objective functions, scalarizations, extra functions, and constants. This will not find constraints. Args: name (str): The symbol of the expression. Returns: gurobipy expression: A mathematical expression that gp.Model can use either as a constraint or an objective """ if name in self.variables: expression = self.variables[name] elif name in self.objective_functions: expression = self.objective_functions[name] elif name in self.scalarizations: expression = self.scalarizations[name] elif name in self.extra_functions: expression = self.extra_functions[name] elif name in self.constants: if isinstance(self.constants[name], list): expression = np.array(self.constants[name]) else: expression = self.constants[name] else: msg = f"No expression with name {name} found in the gurobipy model." raise GurobipyEvaluatorError(msg) return expression ``` ##### get_values ``` get_values() -> dict[ str, float | int | bool | list[float] | list[int] ] ``` Get the values from the Gurobipy Model in a dict. The keys of the dict will be the symbols defined in the problem utilized to initialize the evaluator. Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | int | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def get_values(self) -> dict[str, float | int | bool | list[float] | list[int]]: """Get the values from the Gurobipy Model in a dict. The keys of the dict will be the symbols defined in the problem utilized to initialize the evaluator. Returns: dict[str, float | int | bool]: a dict with keys equivalent to the symbols defined in self.problem. """ result_dict = {} for var in self.problem.variables: result_dict[var.symbol] = self.variables[var.symbol].getAttr(gp.GRB.Attr.X) for obj in self.problem.objectives: result_dict[obj.symbol] = self.objective_functions[obj.symbol].getValue() if self.problem.constants is not None: for con in self.problem.constants: result_dict[con.symbol] = self.constants[con.symbol] if self.problem.extra_funcs is not None: for extra in self.problem.extra_funcs: result_dict[extra.symbol] = self.extra_functions[extra.symbol].getValue() if self.problem.constraints is not None: for const in self.problem.constraints: con = self.constraints[const.symbol] if isinstance(con, gp.MQConstr): slack = con.QCSlack result_dict[const.symbol] = (-np.array(slack)).tolist() if hasattr(slack, "__len__") else -slack elif isinstance(con, gp.MConstr): result_dict[const.symbol] = (-con.Slack).tolist() elif isinstance(con, gp.QConstr): result_dict[const.symbol] = -con.getAttr("QCSlack") else: result_dict[const.symbol] = -con.getAttr("Slack") if self.problem.scalarization_funcs is not None: for scal in self.problem.scalarization_funcs: result_dict[scal.symbol] = self.scalarizations[scal.symbol].getValue() return result_dict ``` ##### init_constants ``` init_constants( problem: Problem, ) -> dict[str, int | float | list[int] | list[float]] ``` Add constants to a GurobipyEvaluator. Gurobi does not really have constants, so this function instead stores them in a dict, that is then stored in the evaluator. This is necessary to get the MathParser to understand the constants used in the problem, but updating them at a later point will not update any expression referencing them. The expressions that have been defined using these constants will keep using the numeric value of the constant at the time when the expression was created. Thus, it might be best to avoid using constants if you are intending to use the gurobipy solver. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which to extract the constants. | *required* | Raises: | Type | Description | | ------------------------ | ---------------------------------------------------- | | `GurobipyEvaluatorError` | when the domain of a constant cannot be figured out. | Returns: | Type | Description | | ---------------- | ----------- | | \`dict\[str, int | float | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def init_constants(self, problem: Problem) -> dict[str, int | float | list[int] | list[float]]: """Add constants to a GurobipyEvaluator. Gurobi does not really have constants, so this function instead stores them in a dict, that is then stored in the evaluator. This is necessary to get the MathParser to understand the constants used in the problem, but updating them at a later point will not update any expression referencing them. The expressions that have been defined using these constants will keep using the numeric value of the constant at the time when the expression was created. Thus, it might be best to avoid using constants if you are intending to use the gurobipy solver. Args: problem (Problem): problem from which to extract the constants. Raises: GurobipyEvaluatorError: when the domain of a constant cannot be figured out. Returns: dict[str, int | float]: a dict containing the constants. """ constants: dict[str, int | float | list[int] | list[float]] = {} for con in problem.constants: if isinstance(con, Constant): constants[con.symbol] = con.value elif isinstance(con, TensorConstant): constants[con.symbol] = con.get_values() return constants ``` ##### init_constraints ``` init_constraints( problem: Problem, model: Model | None = None ) -> dict[str, gp.Constr] ``` Add constraint expressions to a Gurobipy Model. Parameters: | Name | Type | Description | Default | | --------- | --------------- | ---------------------------------------------------------------------- | -------------------------------------------- | | `problem` | `Problem` | the problem from which to extract the constraint function expressions. | *required* | | `model` | \`GurobipyModel | None\` | the GurobipyModel to add the expressions to. | Raises: | Type | Description | | ------------------------ | --------------------------------------------------- | | `GurobipyEvaluatorError` | when an unsupported constraint type is encountered. | Returns: | Name | Type | Description | | ------ | ------------------- | ------------------------------------------------------------ | | `dict` | `dict[str, Constr]` | the dict with the constraint expressions added to the model. | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def init_constraints(self, problem: Problem, model: gp.Model | None = None) -> dict[str, gp.Constr]: """Add constraint expressions to a Gurobipy Model. Args: problem (Problem): the problem from which to extract the constraint function expressions. model (GurobipyModel | None): the GurobipyModel to add the expressions to. Raises: GurobipyEvaluatorError: when an unsupported constraint type is encountered. Returns: dict: the dict with the constraint expressions added to the model. """ for cons in problem.constraints: gp_expr = self.parse(cons.func, callback=self.get_expression_by_name) match con_type := cons.cons_type: case ConstraintTypeEnum.LTE: # constraints in DESDEO are defined such that they must be less than zero gp_expr = _le(gp_expr, 0) case ConstraintTypeEnum.EQ: gp_expr = _eq(gp_expr, 0) case _: msg = f"Constraint type of {con_type} not supported. Must be one of {ConstraintTypeEnum}." raise GurobipyEvaluatorError(msg) self.constraints[cons.symbol] = self.model.addConstr(gp_expr, name=cons.symbol) self.model.update() return self.constraints ``` ##### init_extras ``` init_extras( problem: Problem, ) -> dict[ str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr | gp.GenExpr | int | float, ] ``` Add extra function expressions to a Gurobipy Model. Gurobi does not support extra expressions natively, so this function instead stores them in a dict to be used by the evaluator. This is necessary to get the MathParser to understand the extra expressions used in the problem, but updating them at a later point will not update any expression referencing them. The expressions that have been defined using these extra expressions will keep using the value of the extra expression at the time when the expression was created. Thus, it might be best to avoid using extra expressions if you are intending to use the gurobipy solver. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which the extract the extra function expressions. | *required* | Returns: | Name | Type | Description | | --------------- | ---------------- | ----------- | | `GurobipyModel` | \`dict\[str, Var | MVar | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def init_extras( self, problem: Problem ) -> dict[str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr | gp.GenExpr | int | float]: """Add extra function expressions to a Gurobipy Model. Gurobi does not support extra expressions natively, so this function instead stores them in a dict to be used by the evaluator. This is necessary to get the MathParser to understand the extra expressions used in the problem, but updating them at a later point will not update any expression referencing them. The expressions that have been defined using these extra expressions will keep using the value of the extra expression at the time when the expression was created. Thus, it might be best to avoid using extra expressions if you are intending to use the gurobipy solver. Args: problem (Problem): problem from which the extract the extra function expressions. Returns: GurobipyModel: the GurobipyModel with the expressions added as attributes. """ for extra in problem.extra_funcs: self.extra_functions[extra.symbol] = self.parse(extra.func, callback=self.get_expression_by_name) return self.extra_functions ``` ##### init_objectives ``` init_objectives( problem: Problem, ) -> dict[ str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr, ] ``` Add objective function expressions to a Gurobipy Model. Does not yet add any actual gurobipy optimization objectives, only creates a dict containing the expressions of the objectives. The objective expressions are stored in the evaluator and appropiate gurobipy objective must be added to the model before solving. Parameters: | Name | Type | Description | Default | | --------- | --------- | ---------------------------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which to extract the objective function expresions. | *required* | Returns: | Name | Type | Description | | ------ | ---------------- | ----------- | | `dict` | \`dict\[str, Var | MVar | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def init_objectives( self, problem: Problem ) -> dict[str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr]: """Add objective function expressions to a Gurobipy Model. Does not yet add any actual gurobipy optimization objectives, only creates a dict containing the expressions of the objectives. The objective expressions are stored in the evaluator and appropiate gurobipy objective must be added to the model before solving. Args: problem (Problem): problem from which to extract the objective function expresions. Returns: dict: dict containing the objective functions. """ for obj in problem.objectives: self.add_objective(obj) return self.objective_functions ``` ##### init_scalarizations ``` init_scalarizations( problem: Problem, ) -> dict[ str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr, ] ``` Add scalrization expressions to a gurobipy model. Scalarizations work identically to objectives, except they are stored in a different dict in the GurobipyModel. If you want to solve the problem using a scalarization, the evaluator needs to set it as an optimization target first. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem from which to extract the scalarization function expressions. | *required* | Returns: | Name | Type | Description | | ------ | ---------------- | ----------- | | `dict` | \`dict\[str, Var | MVar | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def init_scalarizations( self, problem: Problem ) -> dict[str, gp.Var | gp.MVar | gp.LinExpr | gp.QuadExpr | gp.MLinExpr | gp.MQuadExpr]: """Add scalrization expressions to a gurobipy model. Scalarizations work identically to objectives, except they are stored in a different dict in the GurobipyModel. If you want to solve the problem using a scalarization, the evaluator needs to set it as an optimization target first. Args: problem (Problem): the problem from which to extract the scalarization function expressions. Returns: dict: the dict with the scalarization expressions. Scalarization functions are always minimized. """ for scal in problem.scalarization_funcs: self.add_scalarization_function(scal) return self.scalarizations ``` ##### init_variables ``` init_variables( problem: Problem, ) -> dict[str, gp.Var | gp.MVar] ``` Add variables to the GurobipyModel. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which to extract the variables. | *required* | Raises: | Type | Description | | ------------------------ | ----------------------------------------------------------------------------------------------------------- | | `GurobipyEvaluatorError` | when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. | Returns: | Type | Description | | ---------------- | ----------- | | \`dict\[str, Var | MVar\]\` | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def init_variables(self, problem: Problem) -> dict[str, gp.Var | gp.MVar]: """Add variables to the GurobipyModel. Args: problem (Problem): problem from which to extract the variables. Raises: GurobipyEvaluatorError: when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. Returns: dict[str, gp.Var | gp.MVar]: the variables added to the model. """ variables = {} for var in problem.variables: if isinstance(var, Variable): # handle regular variables lowerbound = var.lowerbound if var.lowerbound is not None else float("-inf") upperbound = var.upperbound if var.upperbound is not None else float("inf") # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer domain = gp.GRB.INTEGER case VariableTypeEnum.real: # variable is real domain = gp.GRB.CONTINUOUS case VariableTypeEnum.binary: domain = gp.GRB.BINARY case _: msg = f"Could not figure out the type for variable {var}." raise GurobipyEvaluatorError(msg) # add the variable to the model gvar = self.model.addVar(lb=lowerbound, ub=upperbound, vtype=domain, name=var.symbol) # set the initial value, if one has been defined if var.initial_value is not None: gvar.setAttr("Start", var.initial_value) variables[var.symbol] = gvar elif isinstance(var, TensorVariable): # handle tensor variables, i.e., vectors etc.. lowerbounds = ( var.get_lowerbound_values() if var.lowerbounds is not None else np.full(var.shape, float("-inf")).tolist() ) upperbounds = ( var.get_upperbound_values() if var.upperbounds is not None else np.full(var.shape, float("inf")).tolist() ) # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer domain = gp.GRB.INTEGER case VariableTypeEnum.real: # variable is real domain = gp.GRB.CONTINUOUS case VariableTypeEnum.binary: domain = gp.GRB.BINARY case _: msg = f"Could not figure out the type for variable {var}." raise GurobipyEvaluatorError(msg) # add the variable to the model gvar = self.model.addMVar( shape=tuple(var.shape), lb=np.array(lowerbounds), ub=np.array(upperbounds), vtype=domain, name=var.symbol, ) # set the initial value, if one has been defined if var.initial_values is not None: gvar.setAttr("Start", np.array(var.get_initial_values())) variables[var.symbol] = gvar # update the model before returning, so that other expressions can reference the variables self.model.update() return variables ``` ##### remove_constraint ``` remove_constraint(symbol: str) ``` Removes a constraint from the model. If removing a lot of constraints or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the stored model directly may be faster. Parameters: | Name | Type | Description | Default | | -------- | ----- | -------------------------------------------------------------- | ---------- | | `symbol` | `str` | a str representing the symbol of the constraint to be removed. | *required* | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def remove_constraint(self, symbol: str): """Removes a constraint from the model. If removing a lot of constraints or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the stored model directly may be faster. Args: symbol (str): a str representing the symbol of the constraint to be removed. """ self.model.remove(self.constraints[symbol]) self.constraints.pop(symbol) self.model.update() ``` ##### remove_variable ``` remove_variable(symbol: str) ``` Removes a variable from the model. If removing a lot of variables or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the stored model directly may be faster. Parameters: | Name | Type | Description | Default | | -------- | ----- | ------------------------------------------------------------ | ---------- | | `symbol` | `str` | a str representing the symbol of the variable to be removed. | *required* | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def remove_variable(self, symbol: str): """Removes a variable from the model. If removing a lot of variables or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the stored model directly may be faster. Args: symbol (str): a str representing the symbol of the variable to be removed. """ self.model.remove(self.variables[symbol]) self.variables.pop(symbol) self.model.update() ``` ##### set_optimization_target ``` set_optimization_target( target: str, maximize: bool = False ) ``` Sets a minimization objective to match the target objective or scalarization of the gurobipy model. Parameters: | Name | Type | Description | Default | | ---------- | ------ | ------------------------------------------------------------------------------------------------------------------------ | ---------- | | `target` | `str` | an str representing a symbol. Needs to match an objective function or scalarization function already found in the model. | *required* | | `maximize` | `bool` | If true, the target function is maximized instead of minimized | `False` | Raises: | Type | Description | | ------------------------ | ------------------------------------------------------------ | | `GurobipyEvaluatorError` | the given target was not an attribute of the gurobipy model. | Source code in `desdeo/problem/gurobipy_evaluator.py` ``` def set_optimization_target(self, target: str, maximize: bool = False): """Sets a minimization objective to match the target objective or scalarization of the gurobipy model. Args: target (str): an str representing a symbol. Needs to match an objective function or scalarization function already found in the model. maximize (bool): If true, the target function is maximized instead of minimized Raises: GurobipyEvaluatorError: the given target was not an attribute of the gurobipy model. """ if target in self.objective_functions: objective = self.problem.get_objective(symbol=target, copy=False) maximize = False if objective is None else bool(objective.maximize) elif target in self.scalarizations: maximize = False else: msg = f"The gurobipy model has no objective or scalarization named {target}." raise GurobipyEvaluatorError(msg) obj_expr = self.get_expression_by_name(target) if maximize: self.model.setObjective(obj_expr, sense=gp.GRB.MAXIMIZE) else: self.model.setObjective(obj_expr) ``` #### GurobipyEvaluatorError Bases: `Exception` Raised when an error within the GurobipyEvaluator class is encountered. Source code in `desdeo/problem/gurobipy_evaluator.py` ``` class GurobipyEvaluatorError(Exception): """Raised when an error within the GurobipyEvaluator class is encountered.""" ``` #### GurobipyEvaluatorWarning Bases: `UserWarning` Raised when the problem contains features that are poorly supported in gurobipy. Source code in `desdeo/problem/gurobipy_evaluator.py` ``` class GurobipyEvaluatorWarning(UserWarning): """Raised when the problem contains features that are poorly supported in gurobipy.""" ``` ## CVXPY evaluator ### desdeo.problem.cvxpy_evaluator Defines an evaluator compatible with the Problem JSON format and transforms it into a CVXPY problem. #### CVXPYEvaluator Defines an evaluator that transforms an instance of Problem into a CVXPY problem. Source code in `desdeo/problem/cvxpy_evaluator.py` ``` class CVXPYEvaluator: """Defines an evaluator that transforms an instance of Problem into a CVXPY problem.""" variables: dict[str, cp.Variable] parameters: dict[str, cp.Parameter] constraints: dict[str, cp.Constraint] constraint_expressions: dict[str, cp.Expression] objective_functions: dict[str, cp.Expression] scalarizations: dict[str, cp.Expression] extra_functions: dict[str, cp.Expression] constants: dict[str, int | float | list[int] | list[float]] problem_model: cp.Problem objective_expr: cp.Expression | None def __init__(self, problem: Problem): """Initialized the evaluator. Args: problem (Problem): the problem to be transformed into a CVXPY problem. """ self.objective_functions = {} self.scalarizations = {} self.extra_functions = {} self.constants = {} self.variables = {} self.parameters = {} self.constraints = {} self.constraint_expressions = {} self.objective_expr = None self.problem_model = None # set the parser self.parse = MathParser(to_format=FormatEnum.cvxpy).parse # Add variables self.variables = self.init_variables(problem) # Add constants as parameters, if any if problem.constants is not None: self.parameters, self.constants = self.init_parameters(problem) # Add extra expressions, if any if problem.extra_funcs is not None: self.extra_functions = self.init_extras(problem) # Add objective function expressions self.objective_functions = self.init_objectives(problem) # Add scalarization functions, if any if problem.scalarization_funcs is not None: self.scalarizations = self.init_scalarizations(problem) # Add constraints, if any if problem.constraints is not None: self.constraints = self.init_constraints(problem) self.problem = problem def init_variables(self, problem: Problem) -> dict[str, cp.Variable]: """Add variables to the CVXPY problem. Args: problem (Problem): problem from which to extract the variables. Raises: CVXPYEvaluatorError: when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. Returns: dict[str, cp.Variable]: the variables for the problem. """ for var in problem.variables: self.add_variable(var) return self.variables def init_parameters( self, problem: Problem ) -> tuple[dict[str, cp.Parameter], dict[str, int | float | list[int] | list[float]]]: """Add constants as CVXPY parameters. CVXPY uses parameters for values that can be changed without redefining the problem. This allows constants to be updated between solves. Args: problem (Problem): problem from which to extract the constants. Raises: CVXPYEvaluatorError: when the domain of a constant cannot be figured out. Returns: tuple: a tuple containing (parameters dict, constants dict). """ parameters: dict[str, cp.Parameter] = {} constants: dict[str, int | float | list[int] | list[float]] = {} for con in problem.constants: if isinstance(con, Constant): param = cp.Parameter(name=con.symbol, nonneg=con.value >= 0) param.value = con.value parameters[con.symbol] = param constants[con.symbol] = con.value elif isinstance(con, TensorConstant): values = con.get_values() param = cp.Parameter(shape=np.array(values).shape, name=con.symbol) param.value = np.array(values) parameters[con.symbol] = param constants[con.symbol] = values return parameters, constants def init_extras(self, problem: Problem) -> dict[str, cp.Expression]: """Add extra function expressions to a CVXPY evaluator. Args: problem (Problem): problem from which the extract the extra function expressions. Returns: dict[str, cp.Expression]: a dict containing the extra function expressions. """ for extra in problem.extra_funcs: self.extra_functions[extra.symbol] = self.parse(extra.func, callback=self.get_expression_by_name) return self.extra_functions def init_objectives(self, problem: Problem) -> dict[str, cp.Expression]: """Add objective function expressions to a CVXPY evaluator. Does not yet add any actual CVXPY optimization objectives, only creates a dict containing the expressions of the objectives. Args: problem (Problem): problem from which to extract the objective function expresions. Returns: dict[str, cp.Expression]: dict containing the objective functions. """ for obj in problem.objectives: self.add_objective(obj) return self.objective_functions def init_constraints(self, problem: Problem) -> dict[str, cp.Constraint]: """Add constraint expressions to a CVXPY problem. Args: problem (Problem): the problem from which to extract the constraint function expressions. Raises: CVXPYEvaluatorError: when an unsupported constraint type is encountered. Returns: dict[str, cp.Constraint]: dict of constraints keyed by symbol. """ for cons in problem.constraints: self.add_constraint(cons) return self.constraints def init_scalarizations(self, problem: Problem) -> dict[str, cp.Expression]: """Add scalarization expressions to a CVXPY evaluator. Scalarizations work identically to objectives, except they are stored in a different dict in the CVXPYEvaluator. Args: problem (Problem): the problem from which to extract the scalarization function expressions. Returns: dict[str, cp.Expression]: the dict with the scalarization expressions. """ for scal in problem.scalarization_funcs: self.add_scalarization_function(scal) return self.scalarizations def add_constraint(self, constraint: Constraint) -> cp.Constraint: """Add a constraint expression to the CVXPY problem. Args: constraint (Constraint): the constraint function expression. Raises: CVXPYEvaluatorError: when an unsupported constraint type is encountered. Returns: cp.Constraint: The CVXPY constraint that was added. """ expr = self.parse(constraint.func, self.get_expression_by_name) self.constraint_expressions[constraint.symbol] = expr match constraint.cons_type: case ConstraintTypeEnum.LTE: cvxpy_constraint = expr <= 0 case ConstraintTypeEnum.EQ: cvxpy_constraint = expr == 0 case _: msg = f"Constraint type of {constraint.cons_type} not supported. Must be one of {ConstraintTypeEnum}." raise CVXPYEvaluatorError(msg) self.constraints[constraint.symbol] = cvxpy_constraint return cvxpy_constraint def add_objective(self, obj: Objective): """Adds an objective function expression to the CVXPY evaluator. Does not yet add any actual CVXPY optimization objectives, only adds them to the dict containing the expressions of the objectives. Args: obj (Objective): the objective function expression to be added. """ expr = self.parse(obj.func, self.get_expression_by_name) if isinstance(expr, (int, float)): warnings.warn( "One or more of the problem objectives seems to be a constant.", CVXPYEvaluatorWarning, stacklevel=2, ) self.objective_functions[obj.symbol] = expr # the obj.symbol_min objectives are used when optimizing and building scalarizations etc... self.objective_functions[f"{obj.symbol}_min"] = -(expr) if obj.maximize else expr def add_scalarization_function(self, scal: ScalarizationFunction): """Adds a scalarization expression to the CVXPY evaluator. Scalarizations work identically to objectives, except they are stored in a different dict in the CVXPYEvaluator. Args: scal (ScalarizationFunction): The scalarization function to be added. """ self.scalarizations[scal.symbol] = self.parse(scal.func, self.get_expression_by_name) def add_variable(self, var: Variable | TensorVariable) -> cp.Variable: """Add a variable to the CVXPY evaluator. Args: var (Variable | TensorVariable): The definition of the variable to be added. Raises: CVXPYEvaluatorError: when a problem in extracting the variables is encountered. Returns: cp.Variable: the variable that was added. """ if isinstance(var, Variable): # handle regular variables lowerbound = var.lowerbound upperbound = var.upperbound # Set bounds bounds = None if lowerbound is not None or upperbound is not None: lb = lowerbound if lowerbound is not None else -np.inf ub = upperbound if upperbound is not None else np.inf bounds = [lb, ub] # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer cv_var = cp.Variable(integer=True, bounds=bounds, name=var.symbol) case VariableTypeEnum.real: # variable is real cv_var = cp.Variable(bounds=bounds, name=var.symbol) case VariableTypeEnum.binary: cv_var = cp.Variable(boolean=True, bounds=bounds, name=var.symbol) case _: msg = f"Could not figure out the type for variable {var}." raise CVXPYEvaluatorError(msg) elif isinstance(var, TensorVariable): # handle tensor variables, i.e., vectors etc.. lowerbounds = var.get_lowerbound_values() if var.lowerbounds is not None else None upperbounds = var.get_upperbound_values() if var.upperbounds is not None else None # Set bounds bounds = None if lowerbounds is not None or upperbounds is not None: lb = np.array(lowerbounds) if lowerbounds is not None else -np.inf ub = np.array(upperbounds) if upperbounds is not None else np.inf bounds = [lb, ub] # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer cv_var = cp.Variable(shape=tuple(var.shape), integer=True, bounds=bounds, name=var.symbol) case VariableTypeEnum.real: # variable is real cv_var = cp.Variable(shape=tuple(var.shape), bounds=bounds, name=var.symbol) case VariableTypeEnum.binary: cv_var = cp.Variable(shape=tuple(var.shape), boolean=True, bounds=bounds, name=var.symbol) case _: msg = f"Could not figure out the type for variable {var}." raise CVXPYEvaluatorError(msg) self.variables[var.symbol] = cv_var return cv_var def get_expression_by_name(self, name: str) -> cp.Expression | np.ndarray | int | float: """Returns a CVXPY expression corresponding to the name. Looks for variables, parameters, objective functions, scalarizations, and extra functions. Args: name (str): The symbol of the expression. Returns: cp.Expression | np.ndarray | int | float: A mathematical expression that CVXPY can use. """ if name in self.variables: expression = self.variables[name] elif name in self.parameters: expression = self.parameters[name] elif name in self.objective_functions: expression = self.objective_functions[name] elif name in self.scalarizations: expression = self.scalarizations[name] elif name in self.extra_functions: expression = self.extra_functions[name] elif name in self.constants: if isinstance(self.constants[name], list): expression = np.array(self.constants[name]) else: expression = self.constants[name] else: msg = f"No expression with name {name} found in the CVXPY model." raise CVXPYEvaluatorError(msg) return expression def get_values(self) -> dict[str, float | int | bool | list[float] | list[int] | np.ndarray]: """Get the values from the CVXPY solution in a dict. The keys of the dict will be the symbols defined in the problem utilized to initialize the evaluator. Can only be called after the problem has been solved. Returns: dict: a dict with keys equivalent to the symbols defined in self.problem. Raises: CVXPYEvaluatorError: if the problem has not been solved yet. """ if self.problem_model is None or self.problem_model.status not in [cp.OPTIMAL, cp.OPTIMAL_INACCURATE]: msg = "Problem has not been solved yet or did not achieve optimal status." raise CVXPYEvaluatorError(msg) result_dict = {} for var in self.problem.variables: value = self.variables[var.symbol].value if value is None: msg = f"Variable {var.symbol} has not been solved yet." raise CVXPYEvaluatorError(msg) result_dict[var.symbol] = value for obj in self.problem.objectives: result_dict[obj.symbol] = self.objective_functions[obj.symbol].value if self.problem.constants is not None: for con in self.problem.constants: result_dict[con.symbol] = self.constants[con.symbol] if self.problem.extra_funcs is not None: for extra in self.problem.extra_funcs: result_dict[extra.symbol] = self.extra_functions[extra.symbol].value if self.problem.scalarization_funcs is not None: for scal in self.problem.scalarization_funcs: result_dict[scal.symbol] = self.scalarizations[scal.symbol].value if self.problem.constraints is not None: for con in self.problem.constraints: result_dict[con.symbol] = self.constraint_expressions[con.symbol].value return result_dict def set_optimization_target(self, target: str): """Sets an optimization objective for the CVXPY problem. Args: target (str): a str representing a symbol. Needs to match an objective function or scalarization Raises: CVXPYEvaluatorError: the given target was not found in the evaluator. """ if target in self.objective_functions: objective = self.problem.get_objective(symbol=target, copy=False) maximize = False if objective is None else bool(objective.maximize) elif target in self.scalarizations: maximize = False else: msg = f"The CVXPY model has no objective or scalarization named {target}." raise CVXPYEvaluatorError(msg) obj_expr = self.get_expression_by_name(target) objective = cp.Maximize(obj_expr) if maximize else cp.Minimize(obj_expr) self.objective_expr = objective self.problem_model = cp.Problem(objective, list(self.constraints.values())) def solve(self, **kwargs: dict[str, any]): """Solve the CVXPY problem. Args: **kwargs (dict[str, any]): additional arguments to pass to cp.Problem.solve(). """ if self.problem_model is None: msg = "No optimization target has been set. Call set_optimization_target() first." raise CVXPYEvaluatorError(msg) if self.problem_model.is_dcp(): self.problem_model.solve(**kwargs) elif self.problem_model.is_dgp(): kwargs["gp"] = True self.problem_model.solve(**kwargs) else: warnings.warn( "The problem does not appear to be DCP or DGP. CVXPY may not be able to solve it.", CVXPYEvaluatorWarning, stacklevel=2, ) self.problem_model.solve(**kwargs) def update_parameter(self, symbol: str, value: int | float | list[int] | list[float] | np.ndarray): """Update the value of a parameter (constant). Args: symbol (str): the symbol of the parameter to update. value: the new value for the parameter. Raises: CVXPYEvaluatorError: if the parameter does not exist. """ if symbol not in self.parameters: msg = f"Parameter {symbol} not found in the evaluator." raise CVXPYEvaluatorError(msg) self.parameters[symbol].value = value if isinstance(value, (list, np.ndarray)): self.constants[symbol] = list(value) if isinstance(value, np.ndarray) else value else: self.constants[symbol] = value ``` ##### __init__ ``` __init__(problem: Problem) ``` Initialized the evaluator. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to be transformed into a CVXPY problem. | *required* | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def __init__(self, problem: Problem): """Initialized the evaluator. Args: problem (Problem): the problem to be transformed into a CVXPY problem. """ self.objective_functions = {} self.scalarizations = {} self.extra_functions = {} self.constants = {} self.variables = {} self.parameters = {} self.constraints = {} self.constraint_expressions = {} self.objective_expr = None self.problem_model = None # set the parser self.parse = MathParser(to_format=FormatEnum.cvxpy).parse # Add variables self.variables = self.init_variables(problem) # Add constants as parameters, if any if problem.constants is not None: self.parameters, self.constants = self.init_parameters(problem) # Add extra expressions, if any if problem.extra_funcs is not None: self.extra_functions = self.init_extras(problem) # Add objective function expressions self.objective_functions = self.init_objectives(problem) # Add scalarization functions, if any if problem.scalarization_funcs is not None: self.scalarizations = self.init_scalarizations(problem) # Add constraints, if any if problem.constraints is not None: self.constraints = self.init_constraints(problem) self.problem = problem ``` ##### add_constraint ``` add_constraint(constraint: Constraint) -> cp.Constraint ``` Add a constraint expression to the CVXPY problem. Parameters: | Name | Type | Description | Default | | ------------ | ------------ | ----------------------------------- | ---------- | | `constraint` | `Constraint` | the constraint function expression. | *required* | Raises: | Type | Description | | --------------------- | --------------------------------------------------- | | `CVXPYEvaluatorError` | when an unsupported constraint type is encountered. | Returns: | Type | Description | | ------------ | --------------------------------------------------- | | `Constraint` | cp.Constraint: The CVXPY constraint that was added. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def add_constraint(self, constraint: Constraint) -> cp.Constraint: """Add a constraint expression to the CVXPY problem. Args: constraint (Constraint): the constraint function expression. Raises: CVXPYEvaluatorError: when an unsupported constraint type is encountered. Returns: cp.Constraint: The CVXPY constraint that was added. """ expr = self.parse(constraint.func, self.get_expression_by_name) self.constraint_expressions[constraint.symbol] = expr match constraint.cons_type: case ConstraintTypeEnum.LTE: cvxpy_constraint = expr <= 0 case ConstraintTypeEnum.EQ: cvxpy_constraint = expr == 0 case _: msg = f"Constraint type of {constraint.cons_type} not supported. Must be one of {ConstraintTypeEnum}." raise CVXPYEvaluatorError(msg) self.constraints[constraint.symbol] = cvxpy_constraint return cvxpy_constraint ``` ##### add_objective ``` add_objective(obj: Objective) ``` Adds an objective function expression to the CVXPY evaluator. Does not yet add any actual CVXPY optimization objectives, only adds them to the dict containing the expressions of the objectives. Parameters: | Name | Type | Description | Default | | ----- | ----------- | ---------------------------------------------- | ---------- | | `obj` | `Objective` | the objective function expression to be added. | *required* | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def add_objective(self, obj: Objective): """Adds an objective function expression to the CVXPY evaluator. Does not yet add any actual CVXPY optimization objectives, only adds them to the dict containing the expressions of the objectives. Args: obj (Objective): the objective function expression to be added. """ expr = self.parse(obj.func, self.get_expression_by_name) if isinstance(expr, (int, float)): warnings.warn( "One or more of the problem objectives seems to be a constant.", CVXPYEvaluatorWarning, stacklevel=2, ) self.objective_functions[obj.symbol] = expr # the obj.symbol_min objectives are used when optimizing and building scalarizations etc... self.objective_functions[f"{obj.symbol}_min"] = -(expr) if obj.maximize else expr ``` ##### add_scalarization_function ``` add_scalarization_function(scal: ScalarizationFunction) ``` Adds a scalarization expression to the CVXPY evaluator. Scalarizations work identically to objectives, except they are stored in a different dict in the CVXPYEvaluator. Parameters: | Name | Type | Description | Default | | ------ | ----------------------- | --------------------------------------- | ---------- | | `scal` | `ScalarizationFunction` | The scalarization function to be added. | *required* | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def add_scalarization_function(self, scal: ScalarizationFunction): """Adds a scalarization expression to the CVXPY evaluator. Scalarizations work identically to objectives, except they are stored in a different dict in the CVXPYEvaluator. Args: scal (ScalarizationFunction): The scalarization function to be added. """ self.scalarizations[scal.symbol] = self.parse(scal.func, self.get_expression_by_name) ``` ##### add_variable ``` add_variable(var: Variable | TensorVariable) -> cp.Variable ``` Add a variable to the CVXPY evaluator. Parameters: | Name | Type | Description | Default | | ----- | ---------- | ---------------- | ------------------------------------------- | | `var` | \`Variable | TensorVariable\` | The definition of the variable to be added. | Raises: | Type | Description | | --------------------- | ---------------------------------------------------------- | | `CVXPYEvaluatorError` | when a problem in extracting the variables is encountered. | Returns: | Type | Description | | ---------- | ----------------------------------------- | | `Variable` | cp.Variable: the variable that was added. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def add_variable(self, var: Variable | TensorVariable) -> cp.Variable: """Add a variable to the CVXPY evaluator. Args: var (Variable | TensorVariable): The definition of the variable to be added. Raises: CVXPYEvaluatorError: when a problem in extracting the variables is encountered. Returns: cp.Variable: the variable that was added. """ if isinstance(var, Variable): # handle regular variables lowerbound = var.lowerbound upperbound = var.upperbound # Set bounds bounds = None if lowerbound is not None or upperbound is not None: lb = lowerbound if lowerbound is not None else -np.inf ub = upperbound if upperbound is not None else np.inf bounds = [lb, ub] # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer cv_var = cp.Variable(integer=True, bounds=bounds, name=var.symbol) case VariableTypeEnum.real: # variable is real cv_var = cp.Variable(bounds=bounds, name=var.symbol) case VariableTypeEnum.binary: cv_var = cp.Variable(boolean=True, bounds=bounds, name=var.symbol) case _: msg = f"Could not figure out the type for variable {var}." raise CVXPYEvaluatorError(msg) elif isinstance(var, TensorVariable): # handle tensor variables, i.e., vectors etc.. lowerbounds = var.get_lowerbound_values() if var.lowerbounds is not None else None upperbounds = var.get_upperbound_values() if var.upperbounds is not None else None # Set bounds bounds = None if lowerbounds is not None or upperbounds is not None: lb = np.array(lowerbounds) if lowerbounds is not None else -np.inf ub = np.array(upperbounds) if upperbounds is not None else np.inf bounds = [lb, ub] # figure out the variable type match var.variable_type: case VariableTypeEnum.integer: # variable is integer cv_var = cp.Variable(shape=tuple(var.shape), integer=True, bounds=bounds, name=var.symbol) case VariableTypeEnum.real: # variable is real cv_var = cp.Variable(shape=tuple(var.shape), bounds=bounds, name=var.symbol) case VariableTypeEnum.binary: cv_var = cp.Variable(shape=tuple(var.shape), boolean=True, bounds=bounds, name=var.symbol) case _: msg = f"Could not figure out the type for variable {var}." raise CVXPYEvaluatorError(msg) self.variables[var.symbol] = cv_var return cv_var ``` ##### get_expression_by_name ``` get_expression_by_name( name: str, ) -> cp.Expression | np.ndarray | int | float ``` Returns a CVXPY expression corresponding to the name. Looks for variables, parameters, objective functions, scalarizations, and extra functions. Parameters: | Name | Type | Description | Default | | ------ | ----- | ----------------------------- | ---------- | | `name` | `str` | The symbol of the expression. | *required* | Returns: | Type | Description | | ------------ | ----------- | | \`Expression | ndarray | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def get_expression_by_name(self, name: str) -> cp.Expression | np.ndarray | int | float: """Returns a CVXPY expression corresponding to the name. Looks for variables, parameters, objective functions, scalarizations, and extra functions. Args: name (str): The symbol of the expression. Returns: cp.Expression | np.ndarray | int | float: A mathematical expression that CVXPY can use. """ if name in self.variables: expression = self.variables[name] elif name in self.parameters: expression = self.parameters[name] elif name in self.objective_functions: expression = self.objective_functions[name] elif name in self.scalarizations: expression = self.scalarizations[name] elif name in self.extra_functions: expression = self.extra_functions[name] elif name in self.constants: if isinstance(self.constants[name], list): expression = np.array(self.constants[name]) else: expression = self.constants[name] else: msg = f"No expression with name {name} found in the CVXPY model." raise CVXPYEvaluatorError(msg) return expression ``` ##### get_values ``` get_values() -> dict[ str, float | int | bool | list[float] | list[int] | np.ndarray, ] ``` Get the values from the CVXPY solution in a dict. The keys of the dict will be the symbols defined in the problem utilized to initialize the evaluator. Can only be called after the problem has been solved. Returns: | Name | Type | Description | | ------ | ------------------ | ----------- | | `dict` | \`dict\[str, float | int | Raises: | Type | Description | | --------------------- | --------------------------------------- | | `CVXPYEvaluatorError` | if the problem has not been solved yet. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def get_values(self) -> dict[str, float | int | bool | list[float] | list[int] | np.ndarray]: """Get the values from the CVXPY solution in a dict. The keys of the dict will be the symbols defined in the problem utilized to initialize the evaluator. Can only be called after the problem has been solved. Returns: dict: a dict with keys equivalent to the symbols defined in self.problem. Raises: CVXPYEvaluatorError: if the problem has not been solved yet. """ if self.problem_model is None or self.problem_model.status not in [cp.OPTIMAL, cp.OPTIMAL_INACCURATE]: msg = "Problem has not been solved yet or did not achieve optimal status." raise CVXPYEvaluatorError(msg) result_dict = {} for var in self.problem.variables: value = self.variables[var.symbol].value if value is None: msg = f"Variable {var.symbol} has not been solved yet." raise CVXPYEvaluatorError(msg) result_dict[var.symbol] = value for obj in self.problem.objectives: result_dict[obj.symbol] = self.objective_functions[obj.symbol].value if self.problem.constants is not None: for con in self.problem.constants: result_dict[con.symbol] = self.constants[con.symbol] if self.problem.extra_funcs is not None: for extra in self.problem.extra_funcs: result_dict[extra.symbol] = self.extra_functions[extra.symbol].value if self.problem.scalarization_funcs is not None: for scal in self.problem.scalarization_funcs: result_dict[scal.symbol] = self.scalarizations[scal.symbol].value if self.problem.constraints is not None: for con in self.problem.constraints: result_dict[con.symbol] = self.constraint_expressions[con.symbol].value return result_dict ``` ##### init_constraints ``` init_constraints( problem: Problem, ) -> dict[str, cp.Constraint] ``` Add constraint expressions to a CVXPY problem. Parameters: | Name | Type | Description | Default | | --------- | --------- | ---------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem from which to extract the constraint function expressions. | *required* | Raises: | Type | Description | | --------------------- | --------------------------------------------------- | | `CVXPYEvaluatorError` | when an unsupported constraint type is encountered. | Returns: | Type | Description | | ----------------------- | ---------------------------------------------------------------- | | `dict[str, Constraint]` | dict\[str, cp.Constraint\]: dict of constraints keyed by symbol. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def init_constraints(self, problem: Problem) -> dict[str, cp.Constraint]: """Add constraint expressions to a CVXPY problem. Args: problem (Problem): the problem from which to extract the constraint function expressions. Raises: CVXPYEvaluatorError: when an unsupported constraint type is encountered. Returns: dict[str, cp.Constraint]: dict of constraints keyed by symbol. """ for cons in problem.constraints: self.add_constraint(cons) return self.constraints ``` ##### init_extras ``` init_extras(problem: Problem) -> dict[str, cp.Expression] ``` Add extra function expressions to a CVXPY evaluator. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which the extract the extra function expressions. | *required* | Returns: | Type | Description | | ----------------------- | ----------------------------------------------------------------------------- | | `dict[str, Expression]` | dict\[str, cp.Expression\]: a dict containing the extra function expressions. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def init_extras(self, problem: Problem) -> dict[str, cp.Expression]: """Add extra function expressions to a CVXPY evaluator. Args: problem (Problem): problem from which the extract the extra function expressions. Returns: dict[str, cp.Expression]: a dict containing the extra function expressions. """ for extra in problem.extra_funcs: self.extra_functions[extra.symbol] = self.parse(extra.func, callback=self.get_expression_by_name) return self.extra_functions ``` ##### init_objectives ``` init_objectives( problem: Problem, ) -> dict[str, cp.Expression] ``` Add objective function expressions to a CVXPY evaluator. Does not yet add any actual CVXPY optimization objectives, only creates a dict containing the expressions of the objectives. Parameters: | Name | Type | Description | Default | | --------- | --------- | ---------------------------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which to extract the objective function expresions. | *required* | Returns: | Type | Description | | ----------------------- | -------------------------------------------------------------------- | | `dict[str, Expression]` | dict\[str, cp.Expression\]: dict containing the objective functions. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def init_objectives(self, problem: Problem) -> dict[str, cp.Expression]: """Add objective function expressions to a CVXPY evaluator. Does not yet add any actual CVXPY optimization objectives, only creates a dict containing the expressions of the objectives. Args: problem (Problem): problem from which to extract the objective function expresions. Returns: dict[str, cp.Expression]: dict containing the objective functions. """ for obj in problem.objectives: self.add_objective(obj) return self.objective_functions ``` ##### init_parameters ``` init_parameters( problem: Problem, ) -> tuple[ dict[str, cp.Parameter], dict[str, int | float | list[int] | list[float]], ] ``` Add constants as CVXPY parameters. CVXPY uses parameters for values that can be changed without redefining the problem. This allows constants to be updated between solves. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which to extract the constants. | *required* | Raises: | Type | Description | | --------------------- | ---------------------------------------------------- | | `CVXPYEvaluatorError` | when the domain of a constant cannot be figured out. | Returns: | Name | Type | Description | | ------- | --------------------------------------------- | ----------- | | `tuple` | \`tuple\[dict[str, Parameter], dict\[str, int | float | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def init_parameters( self, problem: Problem ) -> tuple[dict[str, cp.Parameter], dict[str, int | float | list[int] | list[float]]]: """Add constants as CVXPY parameters. CVXPY uses parameters for values that can be changed without redefining the problem. This allows constants to be updated between solves. Args: problem (Problem): problem from which to extract the constants. Raises: CVXPYEvaluatorError: when the domain of a constant cannot be figured out. Returns: tuple: a tuple containing (parameters dict, constants dict). """ parameters: dict[str, cp.Parameter] = {} constants: dict[str, int | float | list[int] | list[float]] = {} for con in problem.constants: if isinstance(con, Constant): param = cp.Parameter(name=con.symbol, nonneg=con.value >= 0) param.value = con.value parameters[con.symbol] = param constants[con.symbol] = con.value elif isinstance(con, TensorConstant): values = con.get_values() param = cp.Parameter(shape=np.array(values).shape, name=con.symbol) param.value = np.array(values) parameters[con.symbol] = param constants[con.symbol] = values return parameters, constants ``` ##### init_scalarizations ``` init_scalarizations( problem: Problem, ) -> dict[str, cp.Expression] ``` Add scalarization expressions to a CVXPY evaluator. Scalarizations work identically to objectives, except they are stored in a different dict in the CVXPYEvaluator. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem from which to extract the scalarization function expressions. | *required* | Returns: | Type | Description | | ----------------------- | ------------------------------------------------------------------------ | | `dict[str, Expression]` | dict\[str, cp.Expression\]: the dict with the scalarization expressions. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def init_scalarizations(self, problem: Problem) -> dict[str, cp.Expression]: """Add scalarization expressions to a CVXPY evaluator. Scalarizations work identically to objectives, except they are stored in a different dict in the CVXPYEvaluator. Args: problem (Problem): the problem from which to extract the scalarization function expressions. Returns: dict[str, cp.Expression]: the dict with the scalarization expressions. """ for scal in problem.scalarization_funcs: self.add_scalarization_function(scal) return self.scalarizations ``` ##### init_variables ``` init_variables(problem: Problem) -> dict[str, cp.Variable] ``` Add variables to the CVXPY problem. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------- | ---------- | | `problem` | `Problem` | problem from which to extract the variables. | *required* | Raises: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------- | | `CVXPYEvaluatorError` | when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. | Returns: | Type | Description | | --------------------- | -------------------------------------------------------- | | `dict[str, Variable]` | dict\[str, cp.Variable\]: the variables for the problem. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def init_variables(self, problem: Problem) -> dict[str, cp.Variable]: """Add variables to the CVXPY problem. Args: problem (Problem): problem from which to extract the variables. Raises: CVXPYEvaluatorError: when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. Returns: dict[str, cp.Variable]: the variables for the problem. """ for var in problem.variables: self.add_variable(var) return self.variables ``` ##### set_optimization_target ``` set_optimization_target(target: str) ``` Sets an optimization objective for the CVXPY problem. Parameters: | Name | Type | Description | Default | | -------- | ----- | ---------------------------------------------------------------------------------- | ---------- | | `target` | `str` | a str representing a symbol. Needs to match an objective function or scalarization | *required* | Raises: | Type | Description | | --------------------- | ------------------------------------------------ | | `CVXPYEvaluatorError` | the given target was not found in the evaluator. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def set_optimization_target(self, target: str): """Sets an optimization objective for the CVXPY problem. Args: target (str): a str representing a symbol. Needs to match an objective function or scalarization Raises: CVXPYEvaluatorError: the given target was not found in the evaluator. """ if target in self.objective_functions: objective = self.problem.get_objective(symbol=target, copy=False) maximize = False if objective is None else bool(objective.maximize) elif target in self.scalarizations: maximize = False else: msg = f"The CVXPY model has no objective or scalarization named {target}." raise CVXPYEvaluatorError(msg) obj_expr = self.get_expression_by_name(target) objective = cp.Maximize(obj_expr) if maximize else cp.Minimize(obj_expr) self.objective_expr = objective self.problem_model = cp.Problem(objective, list(self.constraints.values())) ``` ##### solve ``` solve(**kwargs: dict[str, any]) ``` Solve the CVXPY problem. Parameters: | Name | Type | Description | Default | | ---------- | ---------------- | --------------------------------------------------- | ------- | | `**kwargs` | `dict[str, any]` | additional arguments to pass to cp.Problem.solve(). | `{}` | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def solve(self, **kwargs: dict[str, any]): """Solve the CVXPY problem. Args: **kwargs (dict[str, any]): additional arguments to pass to cp.Problem.solve(). """ if self.problem_model is None: msg = "No optimization target has been set. Call set_optimization_target() first." raise CVXPYEvaluatorError(msg) if self.problem_model.is_dcp(): self.problem_model.solve(**kwargs) elif self.problem_model.is_dgp(): kwargs["gp"] = True self.problem_model.solve(**kwargs) else: warnings.warn( "The problem does not appear to be DCP or DGP. CVXPY may not be able to solve it.", CVXPYEvaluatorWarning, stacklevel=2, ) self.problem_model.solve(**kwargs) ``` ##### update_parameter ``` update_parameter( symbol: str, value: int | float | list[int] | list[float] | ndarray, ) ``` Update the value of a parameter (constant). Parameters: | Name | Type | Description | Default | | -------- | ----- | -------------------------------------- | ---------- | | `symbol` | `str` | the symbol of the parameter to update. | *required* | | `value` | \`int | float | list[int] | Raises: | Type | Description | | --------------------- | -------------------------------- | | `CVXPYEvaluatorError` | if the parameter does not exist. | Source code in `desdeo/problem/cvxpy_evaluator.py` ``` def update_parameter(self, symbol: str, value: int | float | list[int] | list[float] | np.ndarray): """Update the value of a parameter (constant). Args: symbol (str): the symbol of the parameter to update. value: the new value for the parameter. Raises: CVXPYEvaluatorError: if the parameter does not exist. """ if symbol not in self.parameters: msg = f"Parameter {symbol} not found in the evaluator." raise CVXPYEvaluatorError(msg) self.parameters[symbol].value = value if isinstance(value, (list, np.ndarray)): self.constants[symbol] = list(value) if isinstance(value, np.ndarray) else value else: self.constants[symbol] = value ``` #### CVXPYEvaluatorError Bases: `Exception` Raised when an error within the CVXPYEvaluator class is encountered. Source code in `desdeo/problem/cvxpy_evaluator.py` ``` class CVXPYEvaluatorError(Exception): """Raised when an error within the CVXPYEvaluator class is encountered.""" ``` #### CVXPYEvaluatorWarning Bases: `UserWarning` Raised when the problem contains features that are poorly supported in cvxpy. Source code in `desdeo/problem/cvxpy_evaluator.py` ``` class CVXPYEvaluatorWarning(UserWarning): """Raised when the problem contains features that are poorly supported in cvxpy.""" ``` ## Simulator evaluator ### desdeo.problem.simulator_evaluator Evaluators are defined to evaluate simulator based and surrogate based objectives, constraints and extras. #### EvaluatorError Bases: `Exception` Error raised when exceptions are encountered in an Evaluator. Source code in `desdeo/problem/simulator_evaluator.py` ``` class EvaluatorError(Exception): """Error raised when exceptions are encountered in an Evaluator.""" ``` #### SimulatorEvaluator A class for creating evaluators for simulator based and surrogate based objectives, constraints and extras. Source code in `desdeo/problem/simulator_evaluator.py` ``` class SimulatorEvaluator: """A class for creating evaluators for simulator based and surrogate based objectives, constraints and extras.""" def __init__( self, problem: Problem, params: dict[str, dict] | ProviderParams | None = None, surrogate_paths: dict[str, Path] | None = None, ): """Creating an evaluator for simulator based and surrogate based objectives, constraints and extras. Args: problem (Problem): The problem as a pydantic 'Problem' data class. params (dict[str, dict], optional): Parameters for the different simulators used in the problem. Given as dict with the simulators' symbols as keys and the corresponding simulator parameters as a dict as values. Defaults to None. surrogate_paths (dict[str, Path], optional): A dictionary where the keys are the names of the objectives, constraints and extra functions and the values are the paths to the surrogate models saved on disk. The names of the objectives, constraints and extra functions should match the names of the objectives, constraints and extra functions in the problem JSON. Defaults to None. """ self.problem = problem # Built on the first evaluation that needs it and reused after that. Building it parses every # function of the problem, which cost as much as evaluating it: 2 ms of a 6 ms single-solution # evaluation on a 30-variable LZ09 problem, paid on every call by steady-state and MOEA/D loops. self._polars_evaluator: PolarsEvaluator | None = None # store the symbol and min or max multiplier as well (symbol, min/max multiplier [1 | -1]) self.objective_mix_max_mult = [ (objective.symbol, -1 if objective.maximize else 1) for objective in problem.objectives ] # Gather symbols objectives of different types into their own lists self.analytical_symbols = [ obj.symbol for obj in list(filter(lambda x: x.objective_type == ObjectiveTypeEnum.analytical, problem.objectives)) ] self.data_based_symbols = [ obj.symbol for obj in problem.objectives if obj.objective_type == ObjectiveTypeEnum.data_based ] self.simulator_symbols = [ obj.symbol for obj in list(filter(lambda x: x.objective_type == ObjectiveTypeEnum.simulator, problem.objectives)) ] self.surrogate_symbols = [ obj.symbol for obj in list(filter(lambda x: x.objective_type == ObjectiveTypeEnum.surrogate, problem.objectives)) ] if problem.scalarization_funcs is not None: parser = MathParser() self.scalarization_funcs = [ (func.symbol, parser.parse(func.func)) for func in problem.scalarization_funcs if func.symbol is not None ] else: self.scalarization_funcs = [] # Gather any constraints' symbols if problem.constraints is not None: self.analytical_symbols = self.analytical_symbols + [ con.symbol for con in list(filter(lambda x: x.func is not None, problem.constraints)) ] self.simulator_symbols = self.simulator_symbols + [ con.symbol for con in list(filter(lambda x: x.simulator_path is not None, problem.constraints)) ] self.surrogate_symbols = self.surrogate_symbols + [ con.symbol for con in list(filter(lambda x: x.surrogates is not None, problem.constraints)) ] # Gather any extra functions' symbols if problem.extra_funcs is not None: self.analytical_symbols = self.analytical_symbols + [ extra.symbol for extra in list(filter(lambda x: x.func is not None, problem.extra_funcs)) ] self.simulator_symbols = self.simulator_symbols + [ extra.symbol for extra in list(filter(lambda x: x.simulator_path is not None, problem.extra_funcs)) ] self.surrogate_symbols = self.surrogate_symbols + [ extra.symbol for extra in list(filter(lambda x: x.surrogates is not None, problem.extra_funcs)) ] # Gather all the symbols of objectives, constraints and extra functions self.problem_symbols = ( self.analytical_symbols + self.data_based_symbols + self.simulator_symbols + self.surrogate_symbols ) # Gather the possible simulators self.simulators = problem.simulators if problem.simulators is not None else [] # Gather the possibly given parameters if params and not isinstance(params, dict): params = params.model_dump() self.params = {} for sim in self.simulators: sim_params = params.get(sim.name, {}) if params is not None else {} if sim.parameter_options is not None: for key in sim.parameter_options: sim_params[key] = sim.parameter_options[key] self.params[sim.name] = sim_params self.surrogates = {} if surrogate_paths is not None: self._load_surrogates(surrogate_paths) else: self._load_surrogates() if len(self.surrogate_symbols) > 0: missing_surrogates = [] for symbol in self.surrogate_symbols: if symbol not in self.surrogates: missing_surrogates.append(symbol) if len(missing_surrogates) > 0: raise EvaluatorError(f"Some surrogates missing: {missing_surrogates}.") def _evaluate_simulator(self, xs: dict[str, list[int | float]]) -> pl.DataFrame: """Evaluate the problem for the given decision variables using the problem's simulators. Args: xs (dict[str, list[int | float]]): The decision variables for which the functions are to be evaluated. Given as a dictionary with the decision variable symbols as keys and a list of decision variable values as the values. The length of the lists is the number of samples and each list should have the same length (same number of samples). Returns: pl.DataFrame: The objective, constraint and extra function values for the given decision variables as a polars dataframe. The symbols of the objectives, constraints and extra functions are the column names and the length of the columns is the number of samples. Will return those objective, constraint and extra function values that are gained from simulators listed in the problem object. """ res_df = pl.DataFrame() for sim in self.simulators: # gather the possible parameters for the simulator params = self.params.get(sim.name, {}) if sim.file is not None: # call the simulator with the decision variable values and parameters as dicts res = subprocess.run( # noqa: PLW1510, S603 [sys.executable, sim.file, "-d", str(xs), "-p", str(params)], capture_output=True, text=True ) if res.returncode == 0: # gather the simulation results (a dict) into the results dataframe res_df = _safe_hstack(res_df, pl.DataFrame(json.loads(res.stdout))) else: raise EvaluatorError(res.stderr) elif sim.url is not None: # call the endpoint try: if isinstance(xs, pl.DataFrame): # if xs is a polars dataframe, convert it to a dict xs = xs.to_dict(as_series=False) scheme = urlparse(sim.url.url).scheme if scheme in supported_schemes: # desdeo res = _external_resolver.evaluate(sim.url.url, params, xs) res_df = _safe_hstack(res_df, pl.DataFrame(res)) # parse res else: # http, https, etc... res = requests.get( sim.url.url, auth=sim.url.auth, json={"d": xs, "p": params}, timeout=sim.url.timeout ) res.raise_for_status() # raise an error if the request failed res_df = _safe_hstack(res_df, pl.DataFrame(res.json())) except requests.RequestException as e: raise EvaluatorError( f"Failed to call the simulator at {sim.url}. Is the simulator server running?" ) from e # Evaluate the minimization form of the objective functions min_obj_columns = pl.DataFrame() for symbol, min_max_mult in self.objective_mix_max_mult: if symbol in res_df.columns: min_obj_columns = _safe_hstack( min_obj_columns, res_df.select((min_max_mult * pl.col(f"{symbol}")).alias(f"{symbol}_min")) ) res_df = res_df.hstack(min_obj_columns) # If there are scalarization functions, evaluate them as well scalarization_columns = res_df.select(*[expr.alias(symbol) for symbol, expr in self.scalarization_funcs]) return res_df.hstack(scalarization_columns) def _evaluate_surrogates(self, xs: dict[str, list[int | float]]) -> pl.DataFrame: """Evaluate the problem for the given decision variables using the surrogate models. Args: xs (dict[str, list[int | float]]): The decision variables for which the functions are to be evaluated. Given as a dictionary with the decision variable symbols as keys and a list of decision variable values as the values. The length of the lists is the number of samples and each list should have the same length (same number of samples). Returns: pl.DataFrame: The values of the evaluated objectives, constraints and extra functions as a polars dataframe. The uncertainty prediction values are also returned. If a model does not provide uncertainty predictions, then they are set as NaN. """ res = pl.DataFrame() var = np.array([value for _, value in xs.items()]).T # has to be transpose (at least for sklearn models) for symbol in self.surrogates: # get a list of args accepted by the model's predict function accepted_args = getfullargspec(self.surrogates[symbol].predict).args # if "return_std" accepted, gather the uncertainty predictions as well if "return_std" in accepted_args: value, uncertainty = self.surrogates[symbol].predict(var, return_std=True) # otherwise, set the uncertainties as NaN else: value = self.surrogates[symbol].predict(var) uncertainty = np.full(np.shape(value), np.nan) # add the objects, constraints and extra functions into the polars dataframe # values go into columns with the symbol as the column names res = res.with_columns(pl.Series(value).alias(symbol)) # uncertainties go into columns with {symbol}_uncert as the column names res = res.with_columns(pl.Series(uncertainty).alias(f"{symbol}_uncert")) # Evaluate the minimization form of the objective functions min_obj_columns = pl.DataFrame() for symbol, min_max_mult in self.objective_mix_max_mult: if symbol in res.columns: min_obj_columns = _safe_hstack( min_obj_columns, res.select((min_max_mult * pl.col(f"{symbol}")).alias(f"{symbol}_min")) ) res_df = res.hstack(min_obj_columns) # If there are scalarization functions, evaluate them as well scalarization_columns = res_df.select(*[expr.alias(symbol) for symbol, expr in self.scalarization_funcs]) return res_df.hstack(scalarization_columns) def _load_surrogates(self, surrogate_paths: dict[str, Path] | None = None): """Load the surrogate models from disk and store them within the evaluator. This is used during initialization of the evaluator or when the analyst wants to replace the current surrogate models with other models. However if a new model is trained after initialization of the evaluator, the problem JSON should be updated with the new model paths and the evaluator should be re-initialized. This can happen with any solver that does model management. Args: surrogate_paths (dict[str, Path]): A dictionary where the keys are the names of the objectives, constraints and extra functions and the values are the paths to the surrogate models saved on disk. The names of the objectives should match the names of the objectives in the problem JSON. At the moment the supported file format is .skops (through skops.io). TODO: if skops.io used, should be added to pyproject.toml. """ if surrogate_paths is not None: for symbol in surrogate_paths: with Path.open(f"{surrogate_paths[symbol]}", "rb") as file: self.surrogates[symbol] = joblib.load(file) """unknown_types = sio.get_untrusted_types(file=file) if len(unknown_types) == 0: self.surrogates[symbol] = sio.load(file, unknown_types) else: # TODO: if there are unknown types they should be checked self.surrogates[symbol] = sio.load(file, unknown_types) #raise EvaluatorError(f"Untrusted types found in the model of {obj.symbol}: {unknown_types}")""" else: # check each surrogate based objective, constraint and extra function for surrogate path for obj in self.problem.objectives: if obj.surrogates is not None: with Path.open(f"{obj.surrogates[0]}", "rb") as file: self.surrogates[obj.symbol] = joblib.load(file) for con in self.problem.constraints or []: # if there are no constraints, an empty list is used if con.surrogates is not None: with Path.open(f"{con.surrogates[0]}", "rb") as file: self.surrogates[con.symbol] = joblib.load(file) for extra in self.problem.extra_funcs or []: # if there are no extra functions, an empty list is used if extra.surrogates is not None: with Path.open(f"{extra.surrogates[0]}", "rb") as file: self.surrogates[extra.symbol] = joblib.load(file) def evaluate(self, xs: dict[str, list[int | float]], flat: bool = False) -> pl.DataFrame: """Evaluate the functions for the given decision variables. Evaluates analytical, simulation based and surrogate based functions. For now, the evaluator assumes that there are no data based objectives. Args: xs (dict[str, list[int | float]]): The decision variables for which the functions are to be evaluated. Given as a dictionary with the decision variable symbols as keys and a list of decision variable values as the values. The length of the lists is the number of samples and each list should have the same length (same number of samples). flat (bool, optional): whether the valuation is done using flattened variables or not. Defaults to False. Returns: pl.DataFrame: polars dataframe with the evaluated function values. """ # TODO (@gialmisi): Make work with polars dataframes as well in addition to dict. # See, e.g., PolarsEvaluator._polars_evaluate. Then, remove the arg `flat`. res = pl.DataFrame() # Evaluate the analytical functions if len(self.analytical_symbols + self.data_based_symbols) > 0: if self._polars_evaluator is None: self._polars_evaluator = PolarsEvaluator(self.problem, evaluator_mode=PolarsEvaluatorModesEnum.mixed) polars_evaluator = self._polars_evaluator analytical_values = ( polars_evaluator._polars_evaluate(xs) if not flat else polars_evaluator._polars_evaluate_flat(xs) ) # polars >=1.41 rejects hstack onto a 0-height frame, so seed res from the first # result instead of an empty DataFrame. res = analytical_values if res.width == 0 else res.hstack(analytical_values) # Evaluate the simulator based functions if len(self.simulator_symbols) > 0: simulator_values = self._evaluate_simulator(xs) res = simulator_values if res.width == 0 else res.hstack(simulator_values) # Evaluate the surrogate based functions if len(self.surrogate_symbols) > 0: surrogate_values = self._evaluate_surrogates(xs) res = surrogate_values if res.width == 0 else res.hstack(surrogate_values) # Check that everything is evaluated for symbol in self.problem_symbols: if symbol not in res.columns: raise EvaluatorError(f"{symbol} not evaluated.") return res ``` ##### __init__ ``` __init__( problem: Problem, params: dict[str, dict] | ProviderParams | None = None, surrogate_paths: dict[str, Path] | None = None, ) ``` Creating an evaluator for simulator based and surrogate based objectives, constraints and extras. Parameters: | Name | Type | Description | Default | | ----------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem as a pydantic 'Problem' data class. | *required* | | `params` | `dict[str, dict]` | Parameters for the different simulators used in the problem. Given as dict with the simulators' symbols as keys and the corresponding simulator parameters as a dict as values. Defaults to None. | `None` | | `surrogate_paths` | `dict[str, Path]` | A dictionary where the keys are the names of the objectives, constraints and extra functions and the values are the paths to the surrogate models saved on disk. The names of the objectives, constraints and extra functions should match the names of the objectives, constraints and extra functions in the problem JSON. Defaults to None. | `None` | Source code in `desdeo/problem/simulator_evaluator.py` ``` def __init__( self, problem: Problem, params: dict[str, dict] | ProviderParams | None = None, surrogate_paths: dict[str, Path] | None = None, ): """Creating an evaluator for simulator based and surrogate based objectives, constraints and extras. Args: problem (Problem): The problem as a pydantic 'Problem' data class. params (dict[str, dict], optional): Parameters for the different simulators used in the problem. Given as dict with the simulators' symbols as keys and the corresponding simulator parameters as a dict as values. Defaults to None. surrogate_paths (dict[str, Path], optional): A dictionary where the keys are the names of the objectives, constraints and extra functions and the values are the paths to the surrogate models saved on disk. The names of the objectives, constraints and extra functions should match the names of the objectives, constraints and extra functions in the problem JSON. Defaults to None. """ self.problem = problem # Built on the first evaluation that needs it and reused after that. Building it parses every # function of the problem, which cost as much as evaluating it: 2 ms of a 6 ms single-solution # evaluation on a 30-variable LZ09 problem, paid on every call by steady-state and MOEA/D loops. self._polars_evaluator: PolarsEvaluator | None = None # store the symbol and min or max multiplier as well (symbol, min/max multiplier [1 | -1]) self.objective_mix_max_mult = [ (objective.symbol, -1 if objective.maximize else 1) for objective in problem.objectives ] # Gather symbols objectives of different types into their own lists self.analytical_symbols = [ obj.symbol for obj in list(filter(lambda x: x.objective_type == ObjectiveTypeEnum.analytical, problem.objectives)) ] self.data_based_symbols = [ obj.symbol for obj in problem.objectives if obj.objective_type == ObjectiveTypeEnum.data_based ] self.simulator_symbols = [ obj.symbol for obj in list(filter(lambda x: x.objective_type == ObjectiveTypeEnum.simulator, problem.objectives)) ] self.surrogate_symbols = [ obj.symbol for obj in list(filter(lambda x: x.objective_type == ObjectiveTypeEnum.surrogate, problem.objectives)) ] if problem.scalarization_funcs is not None: parser = MathParser() self.scalarization_funcs = [ (func.symbol, parser.parse(func.func)) for func in problem.scalarization_funcs if func.symbol is not None ] else: self.scalarization_funcs = [] # Gather any constraints' symbols if problem.constraints is not None: self.analytical_symbols = self.analytical_symbols + [ con.symbol for con in list(filter(lambda x: x.func is not None, problem.constraints)) ] self.simulator_symbols = self.simulator_symbols + [ con.symbol for con in list(filter(lambda x: x.simulator_path is not None, problem.constraints)) ] self.surrogate_symbols = self.surrogate_symbols + [ con.symbol for con in list(filter(lambda x: x.surrogates is not None, problem.constraints)) ] # Gather any extra functions' symbols if problem.extra_funcs is not None: self.analytical_symbols = self.analytical_symbols + [ extra.symbol for extra in list(filter(lambda x: x.func is not None, problem.extra_funcs)) ] self.simulator_symbols = self.simulator_symbols + [ extra.symbol for extra in list(filter(lambda x: x.simulator_path is not None, problem.extra_funcs)) ] self.surrogate_symbols = self.surrogate_symbols + [ extra.symbol for extra in list(filter(lambda x: x.surrogates is not None, problem.extra_funcs)) ] # Gather all the symbols of objectives, constraints and extra functions self.problem_symbols = ( self.analytical_symbols + self.data_based_symbols + self.simulator_symbols + self.surrogate_symbols ) # Gather the possible simulators self.simulators = problem.simulators if problem.simulators is not None else [] # Gather the possibly given parameters if params and not isinstance(params, dict): params = params.model_dump() self.params = {} for sim in self.simulators: sim_params = params.get(sim.name, {}) if params is not None else {} if sim.parameter_options is not None: for key in sim.parameter_options: sim_params[key] = sim.parameter_options[key] self.params[sim.name] = sim_params self.surrogates = {} if surrogate_paths is not None: self._load_surrogates(surrogate_paths) else: self._load_surrogates() if len(self.surrogate_symbols) > 0: missing_surrogates = [] for symbol in self.surrogate_symbols: if symbol not in self.surrogates: missing_surrogates.append(symbol) if len(missing_surrogates) > 0: raise EvaluatorError(f"Some surrogates missing: {missing_surrogates}.") ``` ##### \_evaluate_simulator ``` _evaluate_simulator( xs: dict[str, list[int | float]], ) -> pl.DataFrame ``` Evaluate the problem for the given decision variables using the problem's simulators. Parameters: | Name | Type | Description | Default | | ---- | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `xs` | \`dict\[str, list\[int | float\]\]\` | The decision variables for which the functions are to be evaluated. Given as a dictionary with the decision variable symbols as keys and a list of decision variable values as the values. The length of the lists is the number of samples and each list should have the same length (same number of samples). | Returns: | Type | Description | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `DataFrame` | pl.DataFrame: The objective, constraint and extra function values for the given decision variables as a polars dataframe. The symbols of the objectives, constraints and extra functions are the column names and the length of the columns is the number of samples. Will return those objective, constraint and extra function values that are gained from simulators listed in the problem object. | Source code in `desdeo/problem/simulator_evaluator.py` ``` def _evaluate_simulator(self, xs: dict[str, list[int | float]]) -> pl.DataFrame: """Evaluate the problem for the given decision variables using the problem's simulators. Args: xs (dict[str, list[int | float]]): The decision variables for which the functions are to be evaluated. Given as a dictionary with the decision variable symbols as keys and a list of decision variable values as the values. The length of the lists is the number of samples and each list should have the same length (same number of samples). Returns: pl.DataFrame: The objective, constraint and extra function values for the given decision variables as a polars dataframe. The symbols of the objectives, constraints and extra functions are the column names and the length of the columns is the number of samples. Will return those objective, constraint and extra function values that are gained from simulators listed in the problem object. """ res_df = pl.DataFrame() for sim in self.simulators: # gather the possible parameters for the simulator params = self.params.get(sim.name, {}) if sim.file is not None: # call the simulator with the decision variable values and parameters as dicts res = subprocess.run( # noqa: PLW1510, S603 [sys.executable, sim.file, "-d", str(xs), "-p", str(params)], capture_output=True, text=True ) if res.returncode == 0: # gather the simulation results (a dict) into the results dataframe res_df = _safe_hstack(res_df, pl.DataFrame(json.loads(res.stdout))) else: raise EvaluatorError(res.stderr) elif sim.url is not None: # call the endpoint try: if isinstance(xs, pl.DataFrame): # if xs is a polars dataframe, convert it to a dict xs = xs.to_dict(as_series=False) scheme = urlparse(sim.url.url).scheme if scheme in supported_schemes: # desdeo res = _external_resolver.evaluate(sim.url.url, params, xs) res_df = _safe_hstack(res_df, pl.DataFrame(res)) # parse res else: # http, https, etc... res = requests.get( sim.url.url, auth=sim.url.auth, json={"d": xs, "p": params}, timeout=sim.url.timeout ) res.raise_for_status() # raise an error if the request failed res_df = _safe_hstack(res_df, pl.DataFrame(res.json())) except requests.RequestException as e: raise EvaluatorError( f"Failed to call the simulator at {sim.url}. Is the simulator server running?" ) from e # Evaluate the minimization form of the objective functions min_obj_columns = pl.DataFrame() for symbol, min_max_mult in self.objective_mix_max_mult: if symbol in res_df.columns: min_obj_columns = _safe_hstack( min_obj_columns, res_df.select((min_max_mult * pl.col(f"{symbol}")).alias(f"{symbol}_min")) ) res_df = res_df.hstack(min_obj_columns) # If there are scalarization functions, evaluate them as well scalarization_columns = res_df.select(*[expr.alias(symbol) for symbol, expr in self.scalarization_funcs]) return res_df.hstack(scalarization_columns) ``` ##### \_evaluate_surrogates ``` _evaluate_surrogates( xs: dict[str, list[int | float]], ) -> pl.DataFrame ``` Evaluate the problem for the given decision variables using the surrogate models. Parameters: | Name | Type | Description | Default | | ---- | ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `xs` | \`dict\[str, list\[int | float\]\]\` | The decision variables for which the functions are to be evaluated. Given as a dictionary with the decision variable symbols as keys and a list of decision variable values as the values. The length of the lists is the number of samples and each list should have the same length (same number of samples). | Returns: | Type | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `DataFrame` | pl.DataFrame: The values of the evaluated objectives, constraints and extra functions as a polars dataframe. The uncertainty prediction values are also returned. If a model does not provide uncertainty predictions, then they are set as NaN. | Source code in `desdeo/problem/simulator_evaluator.py` ``` def _evaluate_surrogates(self, xs: dict[str, list[int | float]]) -> pl.DataFrame: """Evaluate the problem for the given decision variables using the surrogate models. Args: xs (dict[str, list[int | float]]): The decision variables for which the functions are to be evaluated. Given as a dictionary with the decision variable symbols as keys and a list of decision variable values as the values. The length of the lists is the number of samples and each list should have the same length (same number of samples). Returns: pl.DataFrame: The values of the evaluated objectives, constraints and extra functions as a polars dataframe. The uncertainty prediction values are also returned. If a model does not provide uncertainty predictions, then they are set as NaN. """ res = pl.DataFrame() var = np.array([value for _, value in xs.items()]).T # has to be transpose (at least for sklearn models) for symbol in self.surrogates: # get a list of args accepted by the model's predict function accepted_args = getfullargspec(self.surrogates[symbol].predict).args # if "return_std" accepted, gather the uncertainty predictions as well if "return_std" in accepted_args: value, uncertainty = self.surrogates[symbol].predict(var, return_std=True) # otherwise, set the uncertainties as NaN else: value = self.surrogates[symbol].predict(var) uncertainty = np.full(np.shape(value), np.nan) # add the objects, constraints and extra functions into the polars dataframe # values go into columns with the symbol as the column names res = res.with_columns(pl.Series(value).alias(symbol)) # uncertainties go into columns with {symbol}_uncert as the column names res = res.with_columns(pl.Series(uncertainty).alias(f"{symbol}_uncert")) # Evaluate the minimization form of the objective functions min_obj_columns = pl.DataFrame() for symbol, min_max_mult in self.objective_mix_max_mult: if symbol in res.columns: min_obj_columns = _safe_hstack( min_obj_columns, res.select((min_max_mult * pl.col(f"{symbol}")).alias(f"{symbol}_min")) ) res_df = res.hstack(min_obj_columns) # If there are scalarization functions, evaluate them as well scalarization_columns = res_df.select(*[expr.alias(symbol) for symbol, expr in self.scalarization_funcs]) return res_df.hstack(scalarization_columns) ``` ##### \_load_surrogates ``` _load_surrogates( surrogate_paths: dict[str, Path] | None = None, ) ``` Load the surrogate models from disk and store them within the evaluator. This is used during initialization of the evaluator or when the analyst wants to replace the current surrogate models with other models. However if a new model is trained after initialization of the evaluator, the problem JSON should be updated with the new model paths and the evaluator should be re-initialized. This can happen with any solver that does model management. Parameters: | Name | Type | Description | Default | | ----------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------- | | `surrogate_paths` | `dict[str, Path]` | A dictionary where the keys are the names of the objectives, constraints and extra functions and the values are the paths to the surrogate models saved on disk. The names of the objectives should match the names of the objectives in the problem JSON. At the moment the supported file format is .skops (through skops.io). TODO: if skops.io used, should be added to pyproject.toml. | `None` | Source code in `desdeo/problem/simulator_evaluator.py` ``` def _load_surrogates(self, surrogate_paths: dict[str, Path] | None = None): """Load the surrogate models from disk and store them within the evaluator. This is used during initialization of the evaluator or when the analyst wants to replace the current surrogate models with other models. However if a new model is trained after initialization of the evaluator, the problem JSON should be updated with the new model paths and the evaluator should be re-initialized. This can happen with any solver that does model management. Args: surrogate_paths (dict[str, Path]): A dictionary where the keys are the names of the objectives, constraints and extra functions and the values are the paths to the surrogate models saved on disk. The names of the objectives should match the names of the objectives in the problem JSON. At the moment the supported file format is .skops (through skops.io). TODO: if skops.io used, should be added to pyproject.toml. """ if surrogate_paths is not None: for symbol in surrogate_paths: with Path.open(f"{surrogate_paths[symbol]}", "rb") as file: self.surrogates[symbol] = joblib.load(file) """unknown_types = sio.get_untrusted_types(file=file) if len(unknown_types) == 0: self.surrogates[symbol] = sio.load(file, unknown_types) else: # TODO: if there are unknown types they should be checked self.surrogates[symbol] = sio.load(file, unknown_types) #raise EvaluatorError(f"Untrusted types found in the model of {obj.symbol}: {unknown_types}")""" else: # check each surrogate based objective, constraint and extra function for surrogate path for obj in self.problem.objectives: if obj.surrogates is not None: with Path.open(f"{obj.surrogates[0]}", "rb") as file: self.surrogates[obj.symbol] = joblib.load(file) for con in self.problem.constraints or []: # if there are no constraints, an empty list is used if con.surrogates is not None: with Path.open(f"{con.surrogates[0]}", "rb") as file: self.surrogates[con.symbol] = joblib.load(file) for extra in self.problem.extra_funcs or []: # if there are no extra functions, an empty list is used if extra.surrogates is not None: with Path.open(f"{extra.surrogates[0]}", "rb") as file: self.surrogates[extra.symbol] = joblib.load(file) ``` ##### evaluate ``` evaluate( xs: dict[str, list[int | float]], flat: bool = False ) -> pl.DataFrame ``` Evaluate the functions for the given decision variables. Evaluates analytical, simulation based and surrogate based functions. For now, the evaluator assumes that there are no data based objectives. Parameters: | Name | Type | Description | Default | | ------ | ---------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `xs` | \`dict\[str, list\[int | float\]\]\` | The decision variables for which the functions are to be evaluated. Given as a dictionary with the decision variable symbols as keys and a list of decision variable values as the values. The length of the lists is the number of samples and each list should have the same length (same number of samples). | | `flat` | `bool` | whether the valuation is done using flattened variables or not. Defaults to False. | `False` | Returns: | Type | Description | | ----------- | ------------------------------------------------------------------ | | `DataFrame` | pl.DataFrame: polars dataframe with the evaluated function values. | Source code in `desdeo/problem/simulator_evaluator.py` ``` def evaluate(self, xs: dict[str, list[int | float]], flat: bool = False) -> pl.DataFrame: """Evaluate the functions for the given decision variables. Evaluates analytical, simulation based and surrogate based functions. For now, the evaluator assumes that there are no data based objectives. Args: xs (dict[str, list[int | float]]): The decision variables for which the functions are to be evaluated. Given as a dictionary with the decision variable symbols as keys and a list of decision variable values as the values. The length of the lists is the number of samples and each list should have the same length (same number of samples). flat (bool, optional): whether the valuation is done using flattened variables or not. Defaults to False. Returns: pl.DataFrame: polars dataframe with the evaluated function values. """ # TODO (@gialmisi): Make work with polars dataframes as well in addition to dict. # See, e.g., PolarsEvaluator._polars_evaluate. Then, remove the arg `flat`. res = pl.DataFrame() # Evaluate the analytical functions if len(self.analytical_symbols + self.data_based_symbols) > 0: if self._polars_evaluator is None: self._polars_evaluator = PolarsEvaluator(self.problem, evaluator_mode=PolarsEvaluatorModesEnum.mixed) polars_evaluator = self._polars_evaluator analytical_values = ( polars_evaluator._polars_evaluate(xs) if not flat else polars_evaluator._polars_evaluate_flat(xs) ) # polars >=1.41 rejects hstack onto a 0-height frame, so seed res from the first # result instead of an empty DataFrame. res = analytical_values if res.width == 0 else res.hstack(analytical_values) # Evaluate the simulator based functions if len(self.simulator_symbols) > 0: simulator_values = self._evaluate_simulator(xs) res = simulator_values if res.width == 0 else res.hstack(simulator_values) # Evaluate the surrogate based functions if len(self.surrogate_symbols) > 0: surrogate_values = self._evaluate_surrogates(xs) res = surrogate_values if res.width == 0 else res.hstack(surrogate_values) # Check that everything is evaluated for symbol in self.problem_symbols: if symbol not in res.columns: raise EvaluatorError(f"{symbol} not evaluated.") return res ``` #### \_safe_hstack ``` _safe_hstack( left: DataFrame, right: DataFrame ) -> pl.DataFrame ``` Horizontally stack two frames, tolerating an empty (0-column) left frame. polars >=1.41 raises a ShapeError when hstacking a non-empty frame onto an empty DataFrame; older versions adopted the right frame's height. Source code in `desdeo/problem/simulator_evaluator.py` ``` def _safe_hstack(left: pl.DataFrame, right: pl.DataFrame) -> pl.DataFrame: """Horizontally stack two frames, tolerating an empty (0-column) left frame. polars >=1.41 raises a ShapeError when hstacking a non-empty frame onto an empty DataFrame; older versions adopted the right frame's height. """ return right if left.width == 0 else left.hstack(right) ``` ## Utilities Various utilities used across the framework related to the Problem formulation. ### ProblemUtilsError Bases: `Exception` Raised when an exception occurs in one of the utils function. Raised when an exception occurs in one of the utils functions defined in the Problem module. Source code in `desdeo/problem/utils.py` ``` class ProblemUtilsError(Exception): """Raised when an exception occurs in one of the utils function. Raised when an exception occurs in one of the utils functions defined in the Problem module. """ ``` ### add_soft_constraint ``` add_soft_constraint( problem: Problem, constraint: Constraint, symbol: str = "constraint_violation", lte_violation_symbol: str | None = None, gte_violation_symbol: str | None = None, ) -> tuple[Problem, str] ``` Add a constraint as a soft constraint by introducing violation slack variables. Adds non-negative slack variables that absorb constraint violations and accumulates their sum into a minimization objective (the constraint violation objective). For a `<=` constraint `g(x) <= 0` the modified constraint becomes `g(x) - s_lte <= 0` where `s_lte >= 0`. For an `=` constraint `g(x) = 0` the modified constraint becomes `g(x) - s_lte + s_gte = 0` where both `s_lte, s_gte >= 0`. The constraint violation objective is created if it does not already exist in the problem, or updated to include the new slack variables if it does. Parameters: | Name | Type | Description | Default | | ---------------------- | ------------ | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to add the soft constraint to. | *required* | | `constraint` | `Constraint` | the constraint to add as a soft constraint. Must have func defined. | *required* | | `symbol` | `str` | symbol for the constraint violation objective. Defaults to "constraint_violation". | `'constraint_violation'` | | `lte_violation_symbol` | \`str | None\` | symbol for the LTE slack variable. Defaults to f"\_{constraint.symbol}\_lte_violation". | | `gte_violation_symbol` | \`str | None\` | symbol for the GTE slack variable (only used for = constraints). Defaults to f"\_{constraint.symbol}\_gte_violation". | Raises: | Type | Description | | ------------------- | ----------------------------------------------------------------------------------------------------------- | | `ProblemUtilsError` | if constraint.func is None, or if a constraint with the symbol constraint.symbol already exists in problem. | Returns: | Type | Description | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `tuple[Problem, str]` | tuple\[Problem, str\]: a copy of the problem with the soft constraint and violation objective added (or updated), and the symbol of the violation objective. | Source code in `desdeo/problem/utils.py` ``` def add_soft_constraint( problem: Problem, constraint: Constraint, symbol: str = "constraint_violation", lte_violation_symbol: str | None = None, gte_violation_symbol: str | None = None, ) -> tuple[Problem, str]: """Add a constraint as a soft constraint by introducing violation slack variables. Adds non-negative slack variables that absorb constraint violations and accumulates their sum into a minimization objective (the constraint violation objective). For a ``<=`` constraint ``g(x) <= 0`` the modified constraint becomes ``g(x) - s_lte <= 0`` where ``s_lte >= 0``. For an ``=`` constraint ``g(x) = 0`` the modified constraint becomes ``g(x) - s_lte + s_gte = 0`` where both ``s_lte, s_gte >= 0``. The constraint violation objective is created if it does not already exist in the problem, or updated to include the new slack variables if it does. Args: problem (Problem): the problem to add the soft constraint to. constraint (Constraint): the constraint to add as a soft constraint. Must have ``func`` defined. symbol (str): symbol for the constraint violation objective. Defaults to ``"constraint_violation"``. lte_violation_symbol (str | None): symbol for the LTE slack variable. Defaults to ``f"_{constraint.symbol}_lte_violation"``. gte_violation_symbol (str | None): symbol for the GTE slack variable (only used for ``=`` constraints). Defaults to ``f"_{constraint.symbol}_gte_violation"``. Raises: ProblemUtilsError: if ``constraint.func`` is ``None``, or if a constraint with the symbol ``constraint.symbol`` already exists in ``problem``. Returns: tuple[Problem, str]: a copy of the problem with the soft constraint and violation objective added (or updated), and the symbol of the violation objective. """ if constraint.func is None: msg = f"Cannot create soft constraint '{constraint.symbol}': its 'func' field is None." raise ProblemUtilsError(msg) if problem.constraints is not None and any(c.symbol == constraint.symbol for c in problem.constraints): msg = f"A constraint with the symbol '{constraint.symbol}' already exists in the problem." raise ProblemUtilsError(msg) if lte_violation_symbol is None: lte_violation_symbol = f"_{constraint.symbol}_lte_violation" if gte_violation_symbol is None: gte_violation_symbol = f"_{constraint.symbol}_gte_violation" # Build violation slack variables (continuous, lb=0, no upper bound) lte_var = Variable( name=f"LTE violation for constraint '{constraint.symbol}'", symbol=lte_violation_symbol, variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=None, initial_value=0.0, ) new_variables = [*problem.variables, lte_var] new_violation_symbols: list[str] = [lte_violation_symbol] if constraint.cons_type == ConstraintTypeEnum.EQ: gte_var = Variable( name=f"GTE violation for constraint '{constraint.symbol}'", symbol=gte_violation_symbol, variable_type=VariableTypeEnum.real, lowerbound=0, upperbound=None, initial_value=0.0, ) new_variables = [*new_variables, gte_var] new_violation_symbols.append(gte_violation_symbol) # Build the modified constraint func with violation variables absorbed if constraint.cons_type == ConstraintTypeEnum.LTE: modified_func = ["Subtract", constraint.func, lte_violation_symbol] else: # EQ modified_func = ["Add", ["Subtract", constraint.func, lte_violation_symbol], gte_violation_symbol] modified_constraint = constraint.model_copy(update={"func": modified_func}) # Build the constraint violation objective func for this constraint's slack variables. # Use Multiply(1, sym) for a single variable to avoid bare-string backend issues. if len(new_violation_symbols) == 1: violation_func: list = ["Multiply", 1, new_violation_symbols[0]] else: violation_func = ["Add", *new_violation_symbols] # Update an existing violation objective or create a new one existing_objectives = list(problem.objectives) violation_obj_idx = next((i for i, obj in enumerate(existing_objectives) if obj.symbol == symbol), None) if violation_obj_idx is not None: existing_obj = existing_objectives[violation_obj_idx] existing_func = existing_obj.func # Extend the existing sum; if it already starts with Add, just append. if isinstance(existing_func, list) and existing_func[0] == "Add": new_violation_func = [*existing_func, *new_violation_symbols] else: new_violation_func = ["Add", existing_func, *new_violation_symbols] updated_obj = existing_obj.model_copy(update={"func": new_violation_func}) existing_objectives[violation_obj_idx] = updated_obj new_objectives = existing_objectives else: violation_objective = Objective( name="Constraint violation", symbol=symbol, func=violation_func, maximize=False, ) new_objectives = [*existing_objectives, violation_objective] # Append the modified constraint to the problem's constraint list existing_constraints = list(problem.constraints) if problem.constraints is not None else [] new_constraints = [*existing_constraints, modified_constraint] new_problem = Problem.model_validate( problem.model_dump(by_alias=True) | { "variables": new_variables, "objectives": new_objectives, "constraints": new_constraints, } ) return new_problem, symbol ``` ### flatten_variable_dict ``` flatten_variable_dict( problem: Problem, variable_dict: dict[str, float | list] ) -> np.ndarray ``` Flatten a dictionary representing variable values of an instance of `Problem` into a numpy array. Flattens a dictionary representing variable values of an instance of `Problem` into a numpy array. The flattening follows a C-like order. Support the flattening of both `Variable` and `TensorVariable` types. Note that it is assumed that no more than one value is defined for each symbol in `variable_dict` that correspond to the required shape of the underlying variable type. Parameters: | Name | Type | Description | Default | | --------------- | ------------------ | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem instance the decision variables are associated with. | *required* | | `variable_dict` | \`dict\[str, float | list\]\` | a dictionary with its keys being the symbols of the variables defined in the instance of Problem, and the values corresponding to the variables' values. | Raises: | Type | Description | | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | | `ValueError` | the variable_dict does not contain as its keys one or more of the symbols defined for the variables in the instance of Problem. | | `TypeError` | unsupported variable type encountered in the variables defined in the instance of Problem. | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: a 1D numpy array with the variable values unflattened in C-like order. | Source code in `desdeo/problem/utils.py` ``` def flatten_variable_dict(problem: Problem, variable_dict: dict[str, float | list]) -> np.ndarray: """Flatten a dictionary representing variable values of an instance of `Problem` into a numpy array. Flattens a dictionary representing variable values of an instance of `Problem` into a numpy array. The flattening follows a C-like order. Support the flattening of both `Variable` and `TensorVariable` types. Note that it is assumed that no more than one value is defined for each symbol in `variable_dict` that correspond to the required shape of the underlying variable type. Args: problem (Problem): the problem instance the decision variables are associated with. variable_dict (dict[str, float | list]): a dictionary with its keys being the symbols of the variables defined in the instance of `Problem`, and the values corresponding to the variables' values. Raises: ValueError: the `variable_dict` does not contain as its keys one or more of the symbols defined for the variables in the instance of `Problem`. TypeError: unsupported variable type encountered in the variables defined in the instance of `Problem`. Returns: np.ndarray: a 1D numpy array with the variable values unflattened in C-like order. """ tmp = [] for var in problem.variables: if isinstance(var, Variable): # just a regular variable if var.symbol not in variable_dict: msg = f"The variable_dict is missing values for the variable {var.symbol}." raise ValueError(msg) tmp.append([variable_dict[var.symbol]]) continue if isinstance(var, TensorVariable): # tensor variable if var.symbol in variable_dict: # tensor variable is defined in the dict as a tensor tmp = [*tmp, np.array(variable_dict[var.symbol]).flatten(order="C")] continue if any(key.startswith(f"{var.symbol}_") for key in variable_dict): # tensor variable flattened in the dict indices = itertools.product(*[range(1, s + 1) for s in var.shape]) flat_symbols = [f"{var.symbol}_{'_'.join(map(str, index))}" for index in indices] tmp = [*tmp, np.array([variable_dict[s] for s in flat_symbols])] continue msg = f"The variable dict is missing values for the variable {var.symbol}." raise ValueError(msg) msg = f"Unsupported variable type {type(var)} encountered." raise TypeError(msg) return np.concatenate(tmp) ``` ### get_ideal_dict ``` get_ideal_dict(problem: Problem) -> dict[str, float] ``` Return a dict representing a problem's ideal point. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------------- | ---------- | | `problem` | `Problem` | the problem with the ideal point. | *required* | Returns: | Type | Description | | ------------------ | -------------------------------------------------------------------------------- | | `dict[str, float]` | dict\[str, float\]: key are objective funciton symbols, values are ideal values. | Source code in `desdeo/problem/utils.py` ``` def get_ideal_dict(problem: Problem) -> dict[str, float]: """Return a dict representing a problem's ideal point. Args: problem (Problem): the problem with the ideal point. Returns: dict[str, float]: key are objective funciton symbols, values are ideal values. """ return {objective.symbol: objective.ideal for objective in problem.objectives} ``` ### get_nadir_dict ``` get_nadir_dict(problem: Problem) -> dict[str, float] ``` Return a dict representing a problem's nadir point. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------------- | ---------- | | `problem` | `Problem` | the problem with the nadir point. | *required* | Returns: | Type | Description | | ------------------ | -------------------------------------------------------------------------------- | | `dict[str, float]` | dict\[str, float\]: key are objective funciton symbols, values are nadir values. | Source code in `desdeo/problem/utils.py` ``` def get_nadir_dict(problem: Problem) -> dict[str, float]: """Return a dict representing a problem's nadir point. Args: problem (Problem): the problem with the nadir point. Returns: dict[str, float]: key are objective funciton symbols, values are nadir values. """ return {objective.symbol: objective.nadir for objective in problem.objectives} ``` ### numpy_array_to_objective_dict ``` numpy_array_to_objective_dict( problem: Problem, numpy_array: ndarray ) -> dict[str, float] ``` Takes a numpy array with objective function values and return a dict. The reverse of objective_dict_to_numpy_array. Parameters: | Name | Type | Description | Default | | ------------- | --------- | --------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the numpy array represents an objective vector of. | *required* | | `numpy_array` | `ndarray` | the objective vector as a numpy array. The array is squeezed, i.e., axes or length one are removed: \[[42]\] -> [42]. | *required* | Returns: | Type | Description | | ------------------ | ---------------------------------------------------------------------------------------------------------------- | | `dict[str, float]` | dict\[str, float\]: a dict with keys being objective function symbols and value being objective function values. | Source code in `desdeo/problem/utils.py` ``` def numpy_array_to_objective_dict(problem: Problem, numpy_array: np.ndarray) -> dict[str, float]: """Takes a numpy array with objective function values and return a dict. The reverse of objective_dict_to_numpy_array. Args: problem (Problem): the problem the numpy array represents an objective vector of. numpy_array (np.ndarray): the objective vector as a numpy array. The array is squeezed, i.e., axes or length one are removed: [[42]] -> [42]. Returns: dict[str, float]: a dict with keys being objective function symbols and value being objective function values. """ return {objective.symbol: np.squeeze(numpy_array).tolist()[i] for i, objective in enumerate(problem.objectives)} ``` ### objective_dict_to_numpy_array ``` objective_dict_to_numpy_array( problem: Problem, objective_dict: dict[str, float] ) -> np.ndarray ``` Takes a dict with an objective vector and returns a numpy array. Takes a dict with the keys being objective function symbols and the values being the corresponding objective function values. Returns a numpy array with the objective function values in the same order they have been defined in the original problem. Parameters: | Name | Type | Description | Default | | ---------------- | ------------------ | -------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the objective dict belongs to. | *required* | | `objective_dict` | `dict[str, float]` | the dict with the objective function values. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | | `ndarray` | np.ndarray: a numpy array with the objective function values in the order they are present in problem. | Source code in `desdeo/problem/utils.py` ``` def objective_dict_to_numpy_array(problem: Problem, objective_dict: dict[str, float]) -> np.ndarray: """Takes a dict with an objective vector and returns a numpy array. Takes a dict with the keys being objective function symbols and the values being the corresponding objective function values. Returns a numpy array with the objective function values in the same order they have been defined in the original problem. Args: problem (Problem): the problem the objective dict belongs to. objective_dict (dict[str, float]): the dict with the objective function values. Returns: np.ndarray: a numpy array with the objective function values in the order they are present in problem. """ if isinstance(objective_dict[problem.objectives[0].symbol], list): if len(objective_dict[problem.objectives[0].symbol]) != 1: raise ValueError("The objective_dict has multiple values for an objective function") return np.array([objective_dict[objective.symbol][0] for objective in problem.objectives]) return np.array([objective_dict[objective.symbol] for objective in problem.objectives]) ``` ### tensor_constant_from_dataframe ``` tensor_constant_from_dataframe( df: DataFrame, name: str, symbol: str, n_rows: int, column_names: list[str], ) -> TensorConstant ``` Create a TensorConstant from a Polars dataframe. Parameters: | Name | Type | Description | Default | | -------------- | ----------- | -------------------------------------------------------------------------------- | ---------- | | `df` | `DataFrame` | a Polars dataframe with at least the columns in column_names | *required* | | `name` | `str` | name attribute of the created TensorConstant. | *required* | | `symbol` | `str` | symbol attribute of the created TensorConstant. | *required* | | `n_rows` | `int` | the number of rows to read from the dataframe. | *required* | | `column_names` | `list[str]` | the column names in the dataframe from which the constant values will be picked. | *required* | Returns: | Name | Type | Description | | ---------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `TensorConstant` | `TensorConstant` | A TensorConstant instance with values taken from the a given Polars dataframe. The shape of the TensorConstant will be (n_rows, len(column_names)). | Note In the argument `shape` the first element must be either less or equal to the number of rows in `df`. The second element in `shape` must be equal to the number of element in `column_names`. Source code in `desdeo/problem/utils.py` ``` def tensor_constant_from_dataframe( df: pl.DataFrame, name: str, symbol: str, n_rows: int, column_names: list[str] ) -> TensorConstant: """Create a TensorConstant from a Polars dataframe. Args: df (pl.DataFrame): a Polars dataframe with at least the columns in `column_names` name (str): name attribute of the created TensorConstant. symbol (str): symbol attribute of the created TensorConstant. n_rows (int): the number of rows to read from the dataframe. column_names (list[str]): the column names in the dataframe from which the constant values will be picked. Returns: TensorConstant: A TensorConstant instance with values taken from the a given Polars dataframe. The shape of the TensorConstant will be (`n_rows`, len(`column_names`)). Note: In the argument `shape` the first element must be either less or equal to the number of rows in `df`. The second element in `shape` must be equal to the number of element in `column_names`. """ if n_rows > df.shape[0]: # not enough rows in df msg = f"Requested {n_rows} rows, but the dataframe has only {df.shape[0]} rows." raise ProblemUtilsError(msg) if len(column_names) > df.shape[1]: # not enough cols in df msg = f"Requested {len(column_names)} columns, but the dataframe has only {df.shape[1]} columns." raise ProblemUtilsError(msg) for col in column_names: if col not in df.columns: msg = f"The requested column '{col}' is not found in the given dataframe with columns {df.columns}." raise ProblemUtilsError(msg) selected_df = df.select(column_names).head(n_rows) selected_values = [selected_df.to_dict()[col_name].to_list() for col_name in column_names] return TensorConstant(name=name, symbol=symbol, shape=[n_rows, len(column_names)], values=selected_values) ``` ### unflatten_variable_array ``` unflatten_variable_array( problem: Problem, var_array: ndarray ) -> dict[str, float | list] ``` Unflatten a numpy array representing decision variable values. Unflatten a numpy array that represent decision variable values. It is assumed that the unflattened values follow a C-like order when it comes to unflattening values for `TensorVariable`s. Note that `var_array` must be of dimension 1. Parameters: | Name | Type | Description | Default | | ----------- | --------- | -------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem instance the decision variables are associated with. | *required* | | `var_array` | `ndarray` | a flat 1D array of numerical values representing decision variable values. | *required* | Raises: | Type | Description | | ------------ | ------------------------------------------------------------------------------------------ | | `ValueError` | var_array is of some other dimension that 1. | | `IndexError` | var_array has too few elements given the variables defined in the instance of Problem. | | `TypeError` | unsupported variable type encountered in the variables defined in the instance of Problem. | Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | list\]\` | Source code in `desdeo/problem/utils.py` ``` def unflatten_variable_array(problem: Problem, var_array: np.ndarray) -> dict[str, float | list]: """Unflatten a numpy array representing decision variable values. Unflatten a numpy array that represent decision variable values. It is assumed that the unflattened values follow a C-like order when it comes to unflattening values for `TensorVariable`s. Note that `var_array` must be of dimension 1. Args: problem (Problem): the problem instance the decision variables are associated with. var_array (np.ndarray): a flat 1D array of numerical values representing decision variable values. Raises: ValueError: `var_array` is of some other dimension that 1. IndexError: `var_array` has too few elements given the variables defined in the instance of `Problem`. TypeError: unsupported variable type encountered in the variables defined in the instance of `Problem`. Returns: dict[str, float | list]: a dict with keys equal to the symbols of the variables defined in the `Problem` instance, and values equal to the decision variable values as they were defined in `var_array`. """ if (dimension := var_array.ndim) != 1: msg = f"The given variable array must have a dimension of 1. Current {dimension=}" raise ValueError(msg) var_dict = {} array_i = 0 for var in problem.variables: if array_i >= len(var_array): msg = ( "End of variable array reached before all variables in the problem were iterated over. " f"The variable array is too short with length={len(var_array)}." ) raise IndexError(msg) if isinstance(var, Variable): # regular variable, just pick it var_dict[var.symbol] = var_array[array_i].item() array_i += 1 continue if isinstance(var, TensorVariable): # tensor variable, pick row-wise from var_array slice_length = reduce(lambda x1, x2: x1 * x2, var.shape) # product of dimensions flat_values = var_array[array_i : array_i + slice_length] var_dict[var.symbol] = np.reshape(flat_values, var.shape, order="C").tolist() array_i += slice_length continue msg = f"Unsupported variable type {type(var)} encountered." raise TypeError(msg) # check if values remain in var_array if array_i < len(var_array): # some values remain, warn user, but do not raise an error msg = f"Warning, the variable array had some values that were not unflattened: f{['...', *var_array[array_i:]]}" warnings.warn(msg, stacklevel=2) # return the variable dict return var_dict ``` ## Scalarization Defines various functions for scalarizing multiobjective optimization problems. Note that when scalarization functions are defined, they must add the post-fix '\_min' to any symbol representing objective functions so that the maximization or minimization of the corresponding objective functions may be correctly accounted for when computing scalarization function values. ### Op Defines the supported operators in the MathJSON format. Source code in `desdeo/tools/scalarization.py` ``` class Op: """Defines the supported operators in the MathJSON format.""" # TODO: move this to problem/schema.py, make it use this, and import it here from there # Basic arithmetic operators NEGATE = "Negate" ADD = "Add" SUB = "Subtract" MUL = "Multiply" DIV = "Divide" # Exponentation and logarithms EXP = "Exp" LN = "Ln" LB = "Lb" LG = "Lg" LOP = "LogOnePlus" SQRT = "Sqrt" SQUARE = "Square" POW = "Power" # Rounding operators ABS = "Abs" CEIL = "Ceil" FLOOR = "Floor" # Trigonometric operations ARCCOS = "Arccos" ARCCOSH = "Arccosh" ARCSIN = "Arcsin" ARCSINH = "Arcsinh" ARCTAN = "Arctan" ARCTANH = "Arctanh" COS = "Cos" COSH = "Cosh" SIN = "Sin" SINH = "Sinh" TAN = "Tan" TANH = "Tanh" # Comparison operators EQUAL = "Equal" GREATER = "Greater" GREATER_EQUAL = "GreaterEqual" LESS = "Less" LESS_EQUAL = "LessEqual" NOT_EQUAL = "NotEqual" # Other operators MAX = "Max" RATIONAL = "Rational" ``` ### ScalarizationError Bases: `Exception` Raised when issues with creating or adding scalarization functions are encountered. Source code in `desdeo/tools/scalarization.py` ``` class ScalarizationError(Exception): """Raised when issues with creating or adding scalarization functions are encountered.""" ``` ### \_\_create_HDF ``` __create_HDF( y: str, a: float, r: float, d1: float = 0.9, d2: float = 0.1, ) -> str ``` Create a Harrington's one-sided desirability function. Harrington's desirability function is used to compute the desirability of a given value of an objective function based on its aspiration and reservation levels. The desirability function is defined as follows: where The desirability function returns a value between 0 and 1, where higher values indicate more desirable outcomes. I took the equations from the following source: Wagner, T., and Trautmann, H. Integration of preference in hypervolume-based multiobjective evolutionary algorithms by means of desirability functions. IEEE Transactions on Evolutionary Computation 14, 5 (2010), 688-701. Parameters: | Name | Type | Description | Default | | ---- | ------- | ---------------------------------------------------- | ---------- | | `y` | `str` | The objective value to compute the desirability for. | *required* | | `a` | `float` | Aspiration level for the objective. | *required* | | `r` | `float` | Reservation level for the objective. | *required* | | `d1` | `float` | The desirability for the aspiration level. | `0.9` | | `d2` | `float` | The desirability for the reservation level. | `0.1` | Returns: | Name | Type | Description | | ---------- | ---------- | ------------------------------------------------------------ | | `callable` | `Function` | A function that computes the desirability for a given value. | Source code in `desdeo/tools/scalarization.py` ``` def __create_HDF( # noqa: N802 y: str, a: float, r: float, d1: float = 0.9, d2: float = 0.1, ) -> str: r"""Create a Harrington's one-sided desirability function. Harrington's desirability function is used to compute the desirability of a given value of an objective function based on its aspiration and reservation levels. The desirability function is defined as follows: \begin{equation} D(y) = \exp\left(-\exp\left(-b_0 - b_1 y\right)\right), \end{equation} where \begin{align*} b_0 &= -\log(-\log(d_1)) - b_1 a, \\ b_1 &= \frac{\log(-\log(d_2)) - \log(-\log(d_1))}{r - a}. \end{align*} The desirability function returns a value between 0 and 1, where higher values indicate more desirable outcomes. I took the equations from the following source: Wagner, T., and Trautmann, H. Integration of preference in hypervolume-based multiobjective evolutionary algorithms by means of desirability functions. IEEE Transactions on Evolutionary Computation 14, 5 (2010), 688-701. Args: y (str): The objective value to compute the desirability for. a (float): Aspiration level for the objective. r (float): Reservation level for the objective. d1 (float): The desirability for the aspiration level. d2 (float): The desirability for the reservation level. Returns: callable (Function): A function that computes the desirability for a given value. """ if not (0 < d1 < 1 and 0 < d2 < 1): raise ValueError("Desirability values must be between 0 and 1 (exclusive).") if not (a < r): raise ValueError("a must be less than r.") if not d2 < d1: raise ValueError("d2 must be less than d1. Higher desirability should correspond to lower values of y.") b1: float = -np.log(-np.log(d2)) + np.log(-np.log(d1)) / (r - a) b0: float = -np.log(-np.log(d1)) - b1 * a def __HDF(y: float): # noqa: N802 """Compute the desirability for a given value.""" return np.exp(-np.exp(-(b0 + b1 * y))) return f"Exp(-Exp(-({b0} + {b1} * {y})))" ``` ### \_\_create_MDF ``` __create_MDF( y: str, a: float, r: float, d1: float = 0.9, d2: float = 0.1, ) -> str ``` Create MaoMao's desirability function. Distinctions form MaoMao's original function: - The upper and lower bounds of desirability are fixed to 0 and 1, respectively. Parameters: | Name | Type | Description | Default | | ---- | ------- | ---------------------------------------------------- | ---------- | | `y` | `str` | The objective value to compute the desirability for. | *required* | | `a` | `float` | Aspiration level for the objective. | *required* | | `r` | `float` | Reservation level for the objective. | *required* | | `d1` | `float` | The desirability for the aspiration level. | `0.9` | | `d2` | `float` | The desirability for the reservation level. | `0.1` | Returns: | Name | Type | Description | | ---------- | ---------- | ------------------------------------------------------------ | | `callable` | `Function` | A function that computes the desirability for a given value. | Source code in `desdeo/tools/scalarization.py` ``` def __create_MDF(y: str, a: float, r: float, d1: float = 0.9, d2: float = 0.1) -> str: # noqa: N802 """Create MaoMao's desirability function. Distinctions form MaoMao's original function: - The upper and lower bounds of desirability are fixed to 0 and 1, respectively. Args: y (str): The objective value to compute the desirability for. a (float): Aspiration level for the objective. r (float): Reservation level for the objective. d1 (float): The desirability for the aspiration level. d2 (float): The desirability for the reservation level. Returns: callable (Function): A function that computes the desirability for a given value. """ if not (0 < d1 < 1 and 0 < d2 < 1): raise ValueError("Desirability values must be between 0 and 1 (exclusive).") if not (a < r): raise ValueError("a must be less than r.") if not d2 < d1: raise ValueError("d2 must be less than d1. Higher desirability should correspond to lower values of y.") ea = 1 - d1 er = d2 m1 = -ea * ea * (a - r) / (d1 - d2) b1 = -a + ea * (a - r) / (d1 - d2) m2 = (d1 - d2) / (a - r) b2 = (d2 * a - d1 * r) / (a - r) m3 = -er * er * (a - r) / (d1 - d2) b3 = -r - er * (a - r) / (d1 - d2) def MDF1(y): # noqa: N802 """Compute the desirability for a given value.""" if isinstance(y, np.ndarray): return np.array([MDF1(yi) for yi in y]) if y < a: return 1 + m1 / (y + b1) if a <= y <= r: return m2 * y + b2 return m3 / (y + b3) def MDF(y): # noqa: N802 """Compute the desirability for a given value.""" # Same but without the if statements if isinstance(y, np.ndarray): return np.array([MDF(yi) for yi in y]) return ( max(a - y, 0) * (1 + m1 / (y + b1)) / (a - y) + max(y - r, 0) * (m3 / (y + b3)) / (y - r) + max(y - a, 0) * max(r - y, 0) * (m2 * y + b2) / ((y - a) * (r - y)) ) return ( f"Max({a} - {y}, 0) * (1 + {m1} / ({y} + {b1})) / ({a} - {y}) + " f"Max({y} - {r}, 0) * ({m3} / ({y} + {b3})) / ({y} - {r}) + " f"Max({y} - {a}, 0) * Max({r} - {y}, 0) * ({m2} * {y} + {b2}) / " f"(({y} - {a}) * ({r} - {y}))" ) ``` ### add_asf_diff ``` add_asf_diff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, delta: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the differentiable variant of the achievement scalarizing function. \[\\begin{align\*} \\min \\quad & \\alpha + \\rho \\sum\_{i=1}^k \\frac{f_i(\\mathbf{x})}{z_i^\\text{nad} - z_i^{\\star\\star}} \\ \\text{s.t.} \\quad & \\frac{f_i(\\mathbf{x}) - \\bar{z}\_i}{z_i^\\text{nad} - z_i^{\\star\\star}} - \\alpha \\leq 0,\\ & \\mathbf{x} \\in S, \\end{align\*}\] where (f_i) are objective functions, (z_i^{\\star\\star} = z_i^\\star - \\delta) is a component of the utopian point, (\\bar{z}\_i) is a component of the reference point, (\\rho) and (\\delta) are small scalar values, (S) is the feasible solution space of the original problem, and (\\alpha) is an auxiliary variable. References Wierzbicki, A. P. (1982). A mathematical basis for satisficing decision making. Mathematical modelling, 3(5), 391-405. Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_point` | `dict[str, float]` | a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar to define the utopian point. Defaults to 1e-6. | `1e-06` | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Todo Add reference in augmentation term option! Source code in `desdeo/tools/scalarization.py` ``` def add_asf_diff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, delta: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the differentiable variant of the achievement scalarizing function. \begin{align*} \min \quad & \alpha + \rho \sum_{i=1}^k \frac{f_i(\mathbf{x})}{z_i^\text{nad} - z_i^{\star\star}} \\ \text{s.t.} \quad & \frac{f_i(\mathbf{x}) - \bar{z}_i}{z_i^\text{nad} - z_i^{\star\star}} - \alpha \leq 0,\\ & \mathbf{x} \in S, \end{align*} where $f_i$ are objective functions, $z_i^{\star\star} = z_i^\star - \delta$ is a component of the utopian point, $\bar{z}_i$ is a component of the reference point, $\rho$ and $\delta$ are small scalar values, $S$ is the feasible solution space of the original problem, and $\alpha$ is an auxiliary variable. References: Wierzbicki, A. P. (1982). A mathematical basis for satisficing decision making. Mathematical modelling, 3(5), 391-405. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_point (dict[str, float]): a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar to define the utopian point. Defaults to 1e-6. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. Todo: Add reference in augmentation term option! """ # check reference point if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing value for one or more objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) corrected_rp = flip_maximized_objective_values(problem, reference_point) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # define the objective function of the scalarization aug_expr = " + ".join( [ (f"{obj.symbol}_min / ({nadir_point[obj.symbol]} - {ideal_point[obj.symbol] - delta})") for obj in problem.objectives ] ) target_expr = f"_alpha + {rho}*" + f"({aug_expr})" scalarization = ScalarizationFunction( name="ASF scalarization objective function", symbol=symbol, func=target_expr, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) constraints = [] for obj in problem.objectives: expr = ( f"({obj.symbol}_min - {corrected_rp[obj.symbol]}) / " f"({nadir_point[obj.symbol]} - {ideal_point[obj.symbol] - delta}) - _alpha" ) constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_asf_generic_diff ``` add_asf_generic_diff( problem: Problem, symbol: str, reference_point: dict[str, float], weights: dict[str, float], reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the differentiable variant of the generic achievement scalarizing function. [\\begin{align\*} \\min \\quad & \\alpha + \\rho \\sum\_{i=1}^k \\frac{f_i(\\mathbf{x})}{w_i} \\ \\text{s.t.} \\quad & \\frac{f_i(\\mathbf{x}) - q_i}{w_i} - \\alpha \\leq 0,\\ & \\mathbf{x} \\in S, \\end{align\*}] where (f_i) are objective functions, (q_i) is a component of the reference point, and (w_i) are components of the weight vector (which are assumed to be positive), (\\rho) and (\\delta) are small scalar values, (S) is the feasible solution space of the original problem, and (\\alpha) is an auxiliary variable. The summation term in the scalarization is known as the *augmentation term*. If a reference point is chosen to be used in the augmentation term, e.g., a separate reference point for the augmentation term is given (`reference_point_aug`), then the reference point components are subtracted from the objective function values in the nominator of the augmentation term. That is: [\\begin{align\*} \\min \\quad & \\alpha + \\rho \\sum\_{i=1}^k \\frac{f_i(\\mathbf{x}) - q_i}{w_i} \\ \\text{s.t.} \\quad & \\frac{f_i(\\mathbf{x}) - q_i}{w_i} - \\alpha \\leq 0,\\ & \\mathbf{x} \\in S, \\end{align\*}] References Wierzbicki, A. P. (1982). A mathematical basis for satisficing decision making. Mathematical modelling, 3(5), 391-405. Parameters: | Name | Type | Description | Default | | --------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_point` | `dict[str, float]` | a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `weights` | `dict[str, float]` | the weights to be used in the scalarization function. Must be positive. | *required* | | `reference_point_aug` | `dict[str, float]` | a dict with keys corresponding to objective function symbols and values to reference point components for the augmentation term, i.e., aspiration levels. Defeults to None. | `None` | | `weights_aug` | `dict[str, float]` | the weights to be used in the scalarization function's augmentation term. Must be positive. Defaults to None. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/scalarization.py` ``` def add_asf_generic_diff( problem: Problem, symbol: str, reference_point: dict[str, float], weights: dict[str, float], reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the differentiable variant of the generic achievement scalarizing function. \begin{align*} \min \quad & \alpha + \rho \sum_{i=1}^k \frac{f_i(\mathbf{x})}{w_i} \\ \text{s.t.} \quad & \frac{f_i(\mathbf{x}) - q_i}{w_i} - \alpha \leq 0,\\ & \mathbf{x} \in S, \end{align*} where $f_i$ are objective functions, $q_i$ is a component of the reference point, and $w_i$ are components of the weight vector (which are assumed to be positive), $\rho$ and $\delta$ are small scalar values, $S$ is the feasible solution space of the original problem, and $\alpha$ is an auxiliary variable. The summation term in the scalarization is known as the _augmentation term_. If a reference point is chosen to be used in the augmentation term, e.g., a separate reference point for the augmentation term is given (`reference_point_aug`), then the reference point components are subtracted from the objective function values in the nominator of the augmentation term. That is: \begin{align*} \min \quad & \alpha + \rho \sum_{i=1}^k \frac{f_i(\mathbf{x}) - q_i}{w_i} \\ \text{s.t.} \quad & \frac{f_i(\mathbf{x}) - q_i}{w_i} - \alpha \leq 0,\\ & \mathbf{x} \in S, \end{align*} References: Wierzbicki, A. P. (1982). A mathematical basis for satisficing decision making. Mathematical modelling, 3(5), 391-405. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_point (dict[str, float]): a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. weights (dict[str, float]): the weights to be used in the scalarization function. Must be positive. reference_point_aug (dict[str, float], optional): a dict with keys corresponding to objective function symbols and values to reference point components for the augmentation term, i.e., aspiration levels. Defeults to None. weights_aug (dict[str, float], optional): the weights to be used in the scalarization function's augmentation term. Must be positive. Defaults to None. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check reference point if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing a value for one or more objectives." raise ScalarizationError(msg) # check augmentation term reference point if reference_point_aug is not None and not objective_dict_has_all_symbols(problem, reference_point_aug): msg = ( f"The given reference point for the augmentation term {reference_point_aug} " "does not have a component defined for all the objectives." ) raise ScalarizationError(msg) # check the weight vector if not objective_dict_has_all_symbols(problem, weights): msg = f"The given weight vector {weights} is missing a value for one or more objectives." raise ScalarizationError(msg) # check the weight vector for the augmentation term if weights_aug is not None and not objective_dict_has_all_symbols(problem, weights_aug): msg = f"The given weight vector {weights_aug} is missing a value for one or more objectives." raise ScalarizationError(msg) corrected_rp = flip_maximized_objective_values(problem, reference_point) if reference_point_aug is not None: corrected_rp_aug = flip_maximized_objective_values(problem, reference_point_aug) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # define the augmentation term if reference_point_aug is None and weights_aug is None: # no reference point in augmentation term # same weights for both terms aug_expr = " + ".join([f"({obj.symbol}_min / {weights[obj.symbol]})" for obj in problem.objectives]) elif reference_point_aug is None and weights_aug is not None: # different weights provided for augmentation term aug_expr = " + ".join([f"({obj.symbol}_min / {weights_aug[obj.symbol]})" for obj in problem.objectives]) elif reference_point_aug is not None and weights_aug is None: # reference point in augmentation term aug_expr = " + ".join( [ f"(({obj.symbol}_min - {corrected_rp_aug[obj.symbol]}) / {weights[obj.symbol]})" for obj in problem.objectives ] ) else: aug_expr = " + ".join( [ f"(({obj.symbol}_min - {corrected_rp_aug[obj.symbol]}) / {weights_aug[obj.symbol]})" for obj in problem.objectives ] ) target_expr = f"_alpha + {rho}*" + f"({aug_expr})" scalarization = ScalarizationFunction( name="Generic ASF scalarization objective function", symbol=symbol, func=target_expr, is_convex=problem.is_convex, is_linear=problem.is_linear, is_twice_differentiable=problem.is_twice_differentiable, ) constraints = [] for obj in problem.objectives: expr = f"({obj.symbol}_min - {corrected_rp[obj.symbol]}) / {weights[obj.symbol]} - _alpha" # since we are subtracting a constant value, the linearity, convexity, # and differentiability of the objective function, and hence the # constraint, should not change. constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_asf_generic_nondiff ``` add_asf_generic_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], weights: dict[str, float], reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the generic achievement scalarizing function to a problem with the given reference point, and weights. This is the non-differentiable variant of the generic achievement scalarizing function, which means the resulting scalarization function is non-differentiable. Compared to `add_asf_nondiff`, this variant is useful, when the problem being scalarized does not have a defined ideal or nadir point, or both. The weights should be non-zero to avoid zero division. The scalarization is defined as follows: \[\\begin{equation} \\mathcal{S}\_\\text{ASF}(F(\\mathbf{x}); \\mathbf{q}, \\mathbf{w}) = \\underset{i=1,\\ldots,k}{\\text{max}} \\left[ \\frac{f_i(\\mathbf{x}) - q_i}{w_i} \\right] - \\rho\\sum\_{i=1}^{k} \\frac{f_i(\\mathbf{x})}{w_i}, \\end{equation}\] where (\\mathbf{q} = [q_1,\\dots,q_k]) is a reference point, (\\mathbf{w} = [w_1,\\dots,w_k]) are weights, (k) is the number of objective functions, and (\\delta) and (\\rho) are small scalar values. The summation term in the scalarization is known as the *augmentation term*. If a reference point is chosen to be used in the augmentation term, e.g., a separate reference point for the augmentation term is given (`reference_point_aug`), then the reference point components are subtracted from the objective function values in the nominator of the augmentation term. That is: \[\\begin{equation} \\mathcal{S}\_\\text{ASF}(F(\\mathbf{x}); \\mathbf{q}, \\mathbf{w}) = \\underset{i=1,\\ldots,k}{\\text{max}} \\left[ \\frac{f_i(\\mathbf{x}) - q_i}{w_i} \\right] - \\rho\\sum\_{i=1}^{k} \\frac{f_i(\\mathbf{x}) - q_i}{w_i}. \\end{equation}\] Parameters: | Name | Type | Description | Default | | --------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to which the scalarization function should be added. | *required* | | `symbol` | `str` | the symbol to reference the added scalarization function. | *required* | | `reference_point` | `dict[str, float]` | a reference point with as many components as there are objectives. | *required* | | `weights` | `dict[str, float]` | the weights to be used in the scalarization function. must be positive. | *required* | | `reference_point_aug` | `dict[str, float]` | a dict with keys corresponding to objective function symbols and values to reference point components for the augmentation term, i.e., aspiration levels. Defeults to None. | `None` | | `weights_aug` | `dict[str, float]` | the weights to be used in the scalarization function's augmentation term. Must be positive. Defaults to None. | `None` | | `rho` | `float` | the weight factor used in the augmentation term. Defaults to 0.000001. | `1e-06` | Raises: | Type | Description | | -------------------- | ----------------------------------------------------------------------------------------------- | | `ScalarizationError` | If either the reference point or the weights given are missing any of the objective components. | | `ScalarizationError` | If any of the ideal or nadir point values are undefined (None). | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/scalarization.py` ``` def add_asf_generic_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], weights: dict[str, float], reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, rho: float = 0.000001, ) -> tuple[Problem, str]: r"""Adds the generic achievement scalarizing function to a problem with the given reference point, and weights. This is the non-differentiable variant of the generic achievement scalarizing function, which means the resulting scalarization function is non-differentiable. Compared to `add_asf_nondiff`, this variant is useful, when the problem being scalarized does not have a defined ideal or nadir point, or both. The weights should be non-zero to avoid zero division. The scalarization is defined as follows: \begin{equation} \mathcal{S}_\text{ASF}(F(\mathbf{x}); \mathbf{q}, \mathbf{w}) = \underset{i=1,\ldots,k}{\text{max}} \left[ \frac{f_i(\mathbf{x}) - q_i}{w_i} \right] + \rho\sum_{i=1}^{k} \frac{f_i(\mathbf{x})}{w_i}, \end{equation} where $\mathbf{q} = [q_1,\dots,q_k]$ is a reference point, $\mathbf{w} = [w_1,\dots,w_k]$ are weights, $k$ is the number of objective functions, and $\delta$ and $\rho$ are small scalar values. The summation term in the scalarization is known as the _augmentation term_. If a reference point is chosen to be used in the augmentation term, e.g., a separate reference point for the augmentation term is given (`reference_point_aug`), then the reference point components are subtracted from the objective function values in the nominator of the augmentation term. That is: \begin{equation} \mathcal{S}_\text{ASF}(F(\mathbf{x}); \mathbf{q}, \mathbf{w}) = \underset{i=1,\ldots,k}{\text{max}} \left[ \frac{f_i(\mathbf{x}) - q_i}{w_i} \right] + \rho\sum_{i=1}^{k} \frac{f_i(\mathbf{x}) - q_i}{w_i}. \end{equation} Args: problem (Problem): the problem to which the scalarization function should be added. symbol (str): the symbol to reference the added scalarization function. reference_point (dict[str, float]): a reference point with as many components as there are objectives. weights (dict[str, float]): the weights to be used in the scalarization function. must be positive. reference_point_aug (dict[str, float], optional): a dict with keys corresponding to objective function symbols and values to reference point components for the augmentation term, i.e., aspiration levels. Defeults to None. weights_aug (dict[str, float], optional): the weights to be used in the scalarization function's augmentation term. Must be positive. Defaults to None. rho (float, optional): the weight factor used in the augmentation term. Defaults to 0.000001. Raises: ScalarizationError: If either the reference point or the weights given are missing any of the objective components. ScalarizationError: If any of the ideal or nadir point values are undefined (None). Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ # check reference point if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing a value for one or more objectives." raise ScalarizationError(msg) # check augmentation term reference point if reference_point_aug is not None and not objective_dict_has_all_symbols(problem, reference_point_aug): msg = ( f"The given reference point for the augmentation term {reference_point_aug} " "does not have a component defined for all the objectives." ) raise ScalarizationError(msg) # check the weight vector if not objective_dict_has_all_symbols(problem, weights): msg = f"The given weight vector {weights} is missing a value for one or more objectives." raise ScalarizationError(msg) # check the weight vector for the augmentation term if weights_aug is not None and not objective_dict_has_all_symbols(problem, weights_aug): msg = f"The given weight vector {weights_aug} is missing a value for one or more objectives." raise ScalarizationError(msg) # get the corrected reference point corrected_rp = flip_maximized_objective_values(problem, reference_point) if reference_point_aug is not None: corrected_rp_aug = flip_maximized_objective_values(problem, reference_point_aug) # Build the max term max_operands = [ (f"({obj.symbol}_min - {corrected_rp[obj.symbol]}) / ({weights[obj.symbol]})") for obj in problem.objectives ] max_term = f"{Op.MAX}({', '.join(max_operands)})" # Build the augmentation term if reference_point_aug is None and weights_aug is None: # no reference point in augmentation term # same weights for both terms aug_expr = " + ".join([f"({obj.symbol}_min / {weights[obj.symbol]})" for obj in problem.objectives]) elif reference_point_aug is None and weights_aug is not None: # different weights provided for augmentation term aug_expr = " + ".join([f"({obj.symbol}_min / {weights_aug[obj.symbol]})" for obj in problem.objectives]) elif reference_point_aug is not None and weights_aug is None: # reference point in augmentation term aug_expr = " + ".join( [ f"(({obj.symbol}_min - {corrected_rp_aug[obj.symbol]}) / {weights[obj.symbol]})" for obj in problem.objectives ] ) else: aug_expr = " + ".join( [ f"(({obj.symbol}_min - {corrected_rp_aug[obj.symbol]}) / {weights_aug[obj.symbol]})" for obj in problem.objectives ] ) # Collect the terms sf = f"{max_term} + {rho} * ({aug_expr})" # Add the function to the problem scalarization_function = ScalarizationFunction( name="Generic achievement scalarizing function", symbol=symbol, func=sf, is_linear=False, is_convex=False, is_twice_differentiable=False, ) return problem.add_scalarization(scalarization_function), symbol ``` ### add_asf_nondiff ``` add_asf_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, delta: float = 1e-06, rho: float = 1e-06, *, reference_in_aug=False, ) -> tuple[Problem, str] ``` Add the achievement scalarizing function for a problem with the reference point. This is the non-differentiable variant of the achievement scalarizing function, which means the resulting scalarization function is non-differentiable. Requires that the ideal and nadir point have been defined for the problem. The scalarization is defined as follows: \[\\begin{equation} \\mathcal{S}\_\\text{ASF}(F(\\mathbf{x}); \\mathbf{q}, \\mathbf{z}^\\star, \\mathbf{z}^\\text{nad}) = \\underset{i=1,\\ldots,k}{\\text{max}} \\left[ \\frac{f_i(\\mathbf{x}) - q_i}{z^\\text{nad}\_i - (z_i^\\star - \\delta)} \\right] - \\rho\\sum\_{i=1}^{k} \\frac{f_i(\\mathbf{x})}{z_i^\\text{nad} - (z_i^\\star - \\delta)}, \\end{equation}\] where (\\mathbf{q} = [q_1,\\dots,q_k]) is a reference point, (\\mathbf{z^\\star} = [z_1^\\star,\\dots,z_k^\\star]) is the ideal point, (\\mathbf{z}^\\text{nad} = [z_1^\\text{nad},\\dots,z_k^\\text{nad}]) is the nadir point, (k) is the number of objective functions, and (\\delta) and (\\rho) are small scalar values. The summation term in the scalarization is known as the *augmentation term*. If the reference point is chosen to be used in the augmentation term (`reference_in_aug=True`), then the reference point components are subtracted from the objective function values in the nominator of the augmentation term. That is: \[\\begin{equation} \\mathcal{S}\_\\text{ASF}(F(\\mathbf{x}); \\mathbf{q}, \\mathbf{z}^\\star, \\mathbf{z}^\\text{nad}) = \\underset{i=1,\\ldots,k}{\\text{max}} \\left[ \\frac{f_i(\\mathbf{x}) - q_i}{z^\\text{nad}\_i - (z_i^\\star - \\delta)} \\right] - \\rho\\sum\_{i=1}^{k} \\frac{f_i(\\mathbf{x}) - q_i}{z_i^\\text{nad} - (z_i^\\star - \\delta)}. \\end{equation}\] Parameters: | Name | Type | Description | Default | | ------------------ | ------------------ | ----------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to which the scalarization function should be added. | *required* | | `symbol` | `str` | the symbol to reference the added scalarization function. | *required* | | `reference_point` | `dict[str, float]` | a reference point as an objective dict. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | the scalar value used to define the utopian point (ideal - delta). Defaults to 0.000001. | `1e-06` | | `rho` | `float` | the weight factor used in the augmentation term. Defaults to 0.000001. | `1e-06` | | `reference_in_aug` | `bool` | whether the reference point should be used in the augmentation term as well. Defaults to False. | `False` | Raises: | Type | Description | | -------------------- | --------------------------------------------------------------------------------------------------------------------- | | `ScalarizationError` | there are missing elements in the reference point, or if any of the ideal or nadir point values are undefined (None). | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/scalarization.py` ``` def add_asf_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, delta: float = 0.000001, rho: float = 0.000001, *, reference_in_aug=False, ) -> tuple[Problem, str]: r"""Add the achievement scalarizing function for a problem with the reference point. This is the non-differentiable variant of the achievement scalarizing function, which means the resulting scalarization function is non-differentiable. Requires that the ideal and nadir point have been defined for the problem. The scalarization is defined as follows: \begin{equation} \mathcal{S}_\text{ASF}(F(\mathbf{x}); \mathbf{q}, \mathbf{z}^\star, \mathbf{z}^\text{nad}) = \underset{i=1,\ldots,k}{\text{max}} \left[ \frac{f_i(\mathbf{x}) - q_i}{z^\text{nad}_i - (z_i^\star - \delta)} \right] + \rho\sum_{i=1}^{k} \frac{f_i(\mathbf{x})}{z_i^\text{nad} - (z_i^\star - \delta)}, \end{equation} where $\mathbf{q} = [q_1,\dots,q_k]$ is a reference point, $\mathbf{z^\star} = [z_1^\star,\dots,z_k^\star]$ is the ideal point, $\mathbf{z}^\text{nad} = [z_1^\text{nad},\dots,z_k^\text{nad}]$ is the nadir point, $k$ is the number of objective functions, and $\delta$ and $\rho$ are small scalar values. The summation term in the scalarization is known as the _augmentation term_. If the reference point is chosen to be used in the augmentation term (`reference_in_aug=True`), then the reference point components are subtracted from the objective function values in the nominator of the augmentation term. That is: \begin{equation} \mathcal{S}_\text{ASF}(F(\mathbf{x}); \mathbf{q}, \mathbf{z}^\star, \mathbf{z}^\text{nad}) = \underset{i=1,\ldots,k}{\text{max}} \left[ \frac{f_i(\mathbf{x}) - q_i}{z^\text{nad}_i - (z_i^\star - \delta)} \right] + \rho\sum_{i=1}^{k} \frac{f_i(\mathbf{x}) - q_i}{z_i^\text{nad} - (z_i^\star - \delta)}. \end{equation} Args: problem (Problem): the problem to which the scalarization function should be added. symbol (str): the symbol to reference the added scalarization function. reference_point (dict[str, float]): a reference point as an objective dict. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): the scalar value used to define the utopian point (ideal - delta). Defaults to 0.000001. rho (float, optional): the weight factor used in the augmentation term. Defaults to 0.000001. reference_in_aug (bool): whether the reference point should be used in the augmentation term as well. Defaults to False. Raises: ScalarizationError: there are missing elements in the reference point, or if any of the ideal or nadir point values are undefined (None). Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ # check that the reference point has all the objective components if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The given reference point {reference_point} does not have a component defined for all the objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) if any(value is None for value in ideal_point.values()) or any(value is None for value in nadir_point.values()): msg = f"There are undefined values in either the ideal ({ideal_point}) or the nadir point ({nadir_point})." raise ScalarizationError(msg) # Build the max term max_operands = [ ( f"({obj.symbol}_min - {reference_point[obj.symbol]}{' * -1' if obj.maximize else ''}) " f"/ ({nadir_point[obj.symbol]} - ({ideal_point[obj.symbol]} - {delta}))" ) for obj in problem.objectives ] max_term = f"{Op.MAX}({', '.join(max_operands)})" # Build the augmentation term if not reference_in_aug: aug_operands = [ f"{obj.symbol}_min / ({nadir_point[obj.symbol]} - ({ideal_point[obj.symbol]} - {delta}))" for obj in problem.objectives ] else: aug_operands = [ ( f"({obj.symbol}_min - {reference_point[obj.symbol]}{' * -1' if obj.maximize else ''}) " f"/ ({nadir_point[obj.symbol]} - ({ideal_point[obj.symbol]} - {delta}))" ) for obj in problem.objectives ] aug_term = " + ".join(aug_operands) asf_function = f"{max_term} + {rho} * ({aug_term})" # Add the function to the problem scalarization_function = ScalarizationFunction( name="Achievement scalarizing function", symbol=symbol, func=asf_function, is_linear=False, is_convex=False, is_twice_differentiable=False, ) return problem.add_scalarization(scalarization_function), symbol ``` ### add_desirability_funcs ``` add_desirability_funcs( problem: Problem, aspiration_levels: dict[str, float], reservation_levels: dict[str, float], desirability_levels: dict[str, tuple[float, float]] | None = None, desirability_func: Literal[ "Harrington", "MaoMao" ] = "Harrington", ) -> tuple[Problem, list[str]] ``` Adds desirability functions to the problem based on the given aspiration and reservation levels. Note that the desirability functions are added as scalarization functions to the problem. They are also multiplied by -1 to ensure that "desirability" values can be minimized, as is assumed by the optimizers. Parameters: | Name | Type | Description | Default | | --------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | The problem to which the desirability functions should be added. | *required* | | `aspiration_levels` | `dict[str, float]` | A dictionary with keys corresponding to objective function symbols and values to aspiration levels. | *required* | | `reservation_levels` | `dict[str, float]` | A dictionary with keys corresponding to objective function symbols and values to reservation levels. | *required* | | `desirability_levels` | \`dict\[str, tuple[float, float]\] | None\` | A dictionary with keys corresponding to objective function symbols and values to desirability levels, where each value is a tuple of (d1, d2). If not given, the default values for d1 and d2 are used, which are 0.9 and 0.1 respectively. Defaults to None. | | `desirability_func` | `str` | The type of desirability function to use. Currently, only "Harrington" or "MaoMao" is supported. Defaults to "Harrington". | `'Harrington'` | Returns: | Name | Type | Description | | --------- | ----------- | --------------------------------------------------------------------------------------- | | `Problem` | `Problem` | A copy of the problem with the added desirability functions as scalarization functions. | | | `list[str]` | list\[str\]: A list of symbols of the added desirability functions. | Source code in `desdeo/tools/scalarization.py` ``` def add_desirability_funcs( problem: Problem, aspiration_levels: dict[str, float], reservation_levels: dict[str, float], desirability_levels: dict[str, tuple[float, float]] | None = None, desirability_func: Literal["Harrington", "MaoMao"] = "Harrington", ) -> tuple[Problem, list[str]]: """Adds desirability functions to the problem based on the given aspiration and reservation levels. Note that the desirability functions are added as scalarization functions to the problem. They are also multiplied by -1 to ensure that "desirability" values can be minimized, as is assumed by the optimizers. Args: problem (Problem): The problem to which the desirability functions should be added. aspiration_levels (dict[str, float]): A dictionary with keys corresponding to objective function symbols and values to aspiration levels. reservation_levels (dict[str, float]): A dictionary with keys corresponding to objective function symbols and values to reservation levels. desirability_levels (dict[str, tuple[float, float]] | None, optional): A dictionary with keys corresponding to objective function symbols and values to desirability levels, where each value is a tuple of (d1, d2). If not given, the default values for d1 and d2 are used, which are 0.9 and 0.1 respectively. Defaults to None. desirability_func (str, optional): The type of desirability function to use. Currently, only "Harrington" or "MaoMao" is supported. Defaults to "Harrington". Returns: Problem: A copy of the problem with the added desirability functions as scalarization functions. list[str]: A list of symbols of the added desirability functions. """ if desirability_func == "Harrington": create_func = __create_HDF elif desirability_func == "MaoMao": create_func = __create_MDF else: raise ScalarizationError(f"Desirability function {desirability_func} is not supported.") if desirability_levels is None: desirability_levels = {obj.symbol: (0.9, 0.1) for obj in problem.objectives} # check that all objectives have aspiration and reservation levels defined for obj in problem.objectives: if obj.symbol not in aspiration_levels or obj.symbol not in reservation_levels: raise ScalarizationError( f"Objective {obj.symbol} does not have both aspiration and reservation levels defined." ) maximize: dict[str, int] = {obj.symbol: -1 if obj.maximize else 1 for obj in problem.objectives} symbols = [] problem_: Problem = problem.model_copy(deep=True) for obj in problem.objectives: d1, d2 = desirability_levels[obj.symbol] func = ( "- (" + create_func( obj.symbol + "_min", aspiration_levels[obj.symbol] * maximize[obj.symbol], reservation_levels[obj.symbol] * maximize[obj.symbol], d1, d2, ) + ")" ) symbols.append(f"{obj.symbol}_d") scalarization = ScalarizationFunction( name=f"Desirability function for {obj.symbol}", symbol=f"{obj.symbol}_d", func=func, is_linear=False, is_convex=False, is_twice_differentiable=obj.is_twice_differentiable, ) problem_ = problem_.add_scalarization(scalarization) return problem_, symbols ``` ### add_epsilon_constraints ``` add_epsilon_constraints( problem: Problem, symbol: str, constraint_symbols: dict[str, str], objective_symbol: str, epsilons: dict[str, float], ) -> tuple[Problem, str, list[str]] ``` Creates expressions for an epsilon constraints scalarization and constraints. It is assumed that epsilon have been given in a format where each objective is to be minimized. The scalarization is defined as follows: [\\begin{equation} \\begin{aligned} & \\operatorname{min}\_{\\mathbf{x} \\in S} & & f_t(\\mathbf{x}) \\ & \\text{s.t.} & & f_j(\\mathbf{x}) \\leq \\epsilon_j \\text{ for all } j = 1, \\ldots ,k, ; j \\neq t, \\end{aligned} \\end{equation}] where (\\epsilon_j) are the epsilon bounds used in the epsilon constraints (f_j(\\mathbf{x}) \\leq \\epsilon_j), and (k) is the number of objective functions. Parameters: | Name | Type | Description | Default | | -------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to scalarize. | *required* | | `symbol` | `str` | the symbol of the added objective function to be optimized. | *required* | | `constraint_symbols` | `dict[str, str]` | a dict with the symbols to be used with the added constraints. The key indicates the name of the objective function the constraint is related to, and the value is the symbol to be used when defining the constraint. | *required* | | `objective_symbol` | `str` | the objective used as the objective in the epsilon constraint scalarization. | *required* | | `epsilons` | `dict[str, float]` | the epsilon constraint values in a dict with each key being an objective's symbol. The corresponding value is then used as the epsilon value for the respective objective function. | *required* | Raises: | Type | Description | | -------------------- | ------------------------------------------------- | | `ScalarizationError` | objective_symbol not found in problem definition. | Returns: | Type | Description | | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str, list[str]]` | tuple\[Problem, str, list[str]\]: A triple with the first element being a copy of the problem with the added epsilon constraints. The second element is the symbol of the objective to be optimized. The last element is a list with the symbols of the added constraints to the problem. | Source code in `desdeo/tools/scalarization.py` ``` def add_epsilon_constraints( problem: Problem, symbol: str, constraint_symbols: dict[str, str], objective_symbol: str, epsilons: dict[str, float] ) -> tuple[Problem, str, list[str]]: r"""Creates expressions for an epsilon constraints scalarization and constraints. It is assumed that epsilon have been given in a format where each objective is to be minimized. The scalarization is defined as follows: \begin{equation} \begin{aligned} & \operatorname{min}_{\mathbf{x} \in S} & & f_t(\mathbf{x}) \\ & \text{s.t.} & & f_j(\mathbf{x}) \leq \epsilon_j \text{ for all } j = 1, \ldots ,k, \; j \neq t, \end{aligned} \end{equation} where $\epsilon_j$ are the epsilon bounds used in the epsilon constraints $f_j(\mathbf{x}) \leq \epsilon_j$, and $k$ is the number of objective functions. Args: problem (Problem): the problem to scalarize. symbol (str): the symbol of the added objective function to be optimized. constraint_symbols (dict[str, str]): a dict with the symbols to be used with the added constraints. The key indicates the name of the objective function the constraint is related to, and the value is the symbol to be used when defining the constraint. objective_symbol (str): the objective used as the objective in the epsilon constraint scalarization. epsilons (dict[str, float]): the epsilon constraint values in a dict with each key being an objective's symbol. The corresponding value is then used as the epsilon value for the respective objective function. Raises: ScalarizationError: `objective_symbol` not found in problem definition. Returns: tuple[Problem, str, list[str]]: A triple with the first element being a copy of the problem with the added epsilon constraints. The second element is the symbol of the objective to be optimized. The last element is a list with the symbols of the added constraints to the problem. """ if objective_symbol not in (correct_symbols := [objective.symbol for objective in problem.objectives]): msg = f"The given objective symbol {objective_symbol} should be one of {correct_symbols}." raise ScalarizationError(msg) _problem, _ = add_objective_as_scalarization(problem, symbol, objective_symbol) # the epsilons must be given such that each objective function is to be minimized constraints = [ Constraint( name=f"Epsilon for {obj.symbol}", symbol=constraint_symbols[obj.symbol], func=["Add", f"{obj.symbol}_min", ["Negate", epsilons[obj.symbol]]], cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) for obj in problem.objectives if obj.symbol != objective_symbol ] _problem = _problem.add_constraints(constraints) return _problem, symbol, [con.symbol for con in constraints] ``` ### add_guess_sf_diff ``` add_guess_sf_diff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, delta: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the differentiable variant of the GUESS scalarizing function. \[\\begin{align\*} \\min \\quad & \\alpha + \\rho \\sum\_{i=1}^k \\frac{f_i(\\mathbf{x})}{z_i^{nad} - \\bar{z}\_i}, \\quad & \\ \\text{s.t.} \\quad & \\frac{f_i(\\mathbf{x}) - z_i^{nad}}{z_i^{nad} - \\bar{z}\_i} - \\alpha \\leq 0 \\quad & \\forall i \\notin I^{\\diamond},\\ & \\mathbf{x} \\in S, \\end{align\*}\] where (f\_{i}) are objective functions, (z\_{i}^{nad}) is a component of the nadir point, (\\bar{z}\_{i}) is a component of the reference point, (\\rho) is a small scalar value, and (S) is the feasible solution space of the original problem. The index set (I^\\diamond) represents objective vectors whose values are free to change. The indices belonging to this set are interpreted as those objective vectors whose components in the reference point is set to be the the respective nadir point component of the problem. Note that in Buchanan (1997), the GUESS method considers all objective functions, i.e. (I^\\diamond) is an empty set. The functionality to have free-to-change objectives was added in Miettinen & Mäkelä (2006). References Buchanan, J. T. (1997). A naive approach for solving MCDM problems: The GUESS method. Journal of the Operational Research Society, 48, 202-206. Miettinen, K., & Mäkelä, M. M. (2006). Synchronous approach in interactive multiobjective optimization. European Journal of Operational Research, 170(3), 909-922. Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_point` | `dict[str, float]` | a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar value to define the utopian point. Defaults to 1e-6. | `1e-06` | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/scalarization.py` ``` def add_guess_sf_diff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, delta: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the differentiable variant of the GUESS scalarizing function. \begin{align*} \min \quad & \alpha + \rho \sum_{i=1}^k \frac{f_i(\mathbf{x})}{z_i^{nad} - \bar{z}_i}, \quad & \\ \text{s.t.} \quad & \frac{f_i(\mathbf{x}) - z_i^{nad}}{z_i^{nad} - \bar{z}_i} - \alpha \leq 0 \quad & \forall i \notin I^{\diamond},\\ & \mathbf{x} \in S, \end{align*} where $f_{i}$ are objective functions, $z_{i}^{nad}$ is a component of the nadir point, $\bar{z}_{i}$ is a component of the reference point, $\rho$ is a small scalar value, and $S$ is the feasible solution space of the original problem. The index set $I^\diamond$ represents objective vectors whose values are free to change. The indices belonging to this set are interpreted as those objective vectors whose components in the reference point is set to be the the respective nadir point component of the problem. Note that in Buchanan (1997), the GUESS method considers all objective functions, i.e. $I^\diamond$ is an empty set. The functionality to have free-to-change objectives was added in Miettinen & Mäkelä (2006). References: Buchanan, J. T. (1997). A naive approach for solving MCDM problems: The GUESS method. Journal of the Operational Research Society, 48, 202-206. Miettinen, K., & Mäkelä, M. M. (2006). Synchronous approach in interactive multiobjective optimization. European Journal of Operational Research, 170(3), 909-922. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_point (dict[str, float]): a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar value to define the utopian point. Defaults to 1e-6. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check reference point if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing value for one or more objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) corrected_rp = flip_maximized_objective_values(problem, reference_point) # the indices that are free to change, set if component of reference point # has the corresponding nadir value, or if it is greater than the nadir value free_to_change = [ sym for sym in corrected_rp if np.isclose(corrected_rp[sym], nadir_point[sym]) or corrected_rp[sym] > nadir_point[sym] ] # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # define the objective function of the scalarization aug_expr = " + ".join( [ ( # Technically delta should be included (according to the paper), but I'm a rebel and don't want to add it f"{obj.symbol}_min / ({nadir_point[obj.symbol]} - {ideal_point[obj.symbol]})" if obj.symbol in free_to_change else f"{obj.symbol}_min / ({nadir_point[obj.symbol]} - {corrected_rp[obj.symbol]})" ) for obj in problem.objectives ] ) target_expr = f"_alpha + {rho}*" + f"({aug_expr})" scalarization = ScalarizationFunction( name="GUESS scalarization objective function", symbol=symbol, func=target_expr, is_convex=problem.is_convex, is_linear=problem.is_linear, is_twice_differentiable=problem.is_twice_differentiable, ) constraints = [] for obj in problem.objectives: if obj.symbol in free_to_change: # if free to change, then do not add a constraint continue # not free to change, add constraint expr = ( f"({obj.symbol}_min - {nadir_point[obj.symbol]}) / " f"({nadir_point[obj.symbol]} - {corrected_rp[obj.symbol]}) - _alpha" ) constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_guess_sf_nondiff ``` add_guess_sf_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the non-differentiable variant of the GUESS scalarizing function. \[\\begin{align\*} \\underset{\\mathbf{x}}{\\min}\\quad & \\underset{i \\notin I^\\diamond}{\\max} \\left[ \\frac{f_i(\\mathbf{x}) - z_i^{nad}}{z_i^{nad} - \\bar{z}\_i} \\right] - \\rho \\sum\_{i=1}^k \\frac{f_i(\\mathbf{x})}{z_i^{nad} - \\bar{z}\_i}, \\quad & \\ \\text{s.t.}\\quad & \\mathbf{x} \\in S, \\end{align\*}\] where (f\_{i}) are objective functions, (z\_{i}^{nad}) is a component of the nadir point, (\\bar{z}\_{i}) is a component of the reference point, (\\rho) is a small scalar value, and (S) is the feasible solution space of the original problem. The index set (I^\\diamond) represents objective vectors whose values are free to change. The indices belonging to this set are interpreted as those objective vectors whose components in the reference point is set to be the the respective nadir point component of the problem. Note that in Buchanan (1997), the GUESS method considers all objective functions, i.e. (I^\\diamond) is an empty set. The functionality to have free-to-change objectives was added in Miettinen & Mäkelä (2006). References Buchanan, J. T. (1997). A naive approach for solving MCDM problems: The GUESS method. Journal of the Operational Research Society, 48, 202-206. Miettinen, K., & Mäkelä, M. M. (2006). Synchronous approach in interactive multiobjective optimization. European Journal of Operational Research, 170(3), 909-922. Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_point` | `dict[str, float]` | a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/scalarization.py` ``` def add_guess_sf_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the non-differentiable variant of the GUESS scalarizing function. \begin{align*} \underset{\mathbf{x}}{\min}\quad & \underset{i \notin I^\diamond}{\max} \left[ \frac{f_i(\mathbf{x}) - z_i^{nad}}{z_i^{nad} - \bar{z}_i} \right] + \rho \sum_{i=1}^k \frac{f_i(\mathbf{x})}{z_i^{nad} - \bar{z}_i}, \quad & \\ \text{s.t.}\quad & \mathbf{x} \in S, \end{align*} where $f_{i}$ are objective functions, $z_{i}^{nad}$ is a component of the nadir point, $\bar{z}_{i}$ is a component of the reference point, $\rho$ is a small scalar value, and $S$ is the feasible solution space of the original problem. The index set $I^\diamond$ represents objective vectors whose values are free to change. The indices belonging to this set are interpreted as those objective vectors whose components in the reference point is set to be the the respective nadir point component of the problem. Note that in Buchanan (1997), the GUESS method considers all objective functions, i.e. $I^\diamond$ is an empty set. The functionality to have free-to-change objectives was added in Miettinen & Mäkelä (2006). References: Buchanan, J. T. (1997). A naive approach for solving MCDM problems: The GUESS method. Journal of the Operational Research Society, 48, 202-206. Miettinen, K., & Mäkelä, M. M. (2006). Synchronous approach in interactive multiobjective optimization. European Journal of Operational Research, 170(3), 909-922. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_point (dict[str, float]): a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check reference point if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing value for one or more objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) corrected_rp = flip_maximized_objective_values(problem, reference_point) # the indices that are free to change, set if component of reference point # has the corresponding nadir value, or if it is greater than the nadir value free_to_change = [ sym for sym in corrected_rp if np.isclose(corrected_rp[sym], nadir_point[sym]) or corrected_rp[sym] > nadir_point[sym] ] # define the max expression of the scalarization # if the objective symbol belongs to the class I^diamond, then do not add it # to the max expression max_expr = ", ".join( [ ( f"({obj.symbol}_min - {(nadir_point[obj.symbol])}) / " f"({nadir_point[obj.symbol]} - {(corrected_rp[obj.symbol])})" ) for obj in problem.objectives if obj.symbol not in free_to_change ] ) # define the augmentation term aug_expr = " + ".join( [ ( # Technically delta should be included (according to the paper), but I'm a rebel and don't want to add it f"{obj.symbol}_min / ({nadir_point[obj.symbol]} - {ideal_point[obj.symbol]})" if obj.symbol in free_to_change else f"{obj.symbol}_min / ({nadir_point[obj.symbol]} - {corrected_rp[obj.symbol]})" ) for obj in problem.objectives ] ) target_expr = f"{Op.MAX}({max_expr}) + {rho}*({aug_expr})" scalarization = ScalarizationFunction( name="GUESS scalarization objective function", symbol=symbol, func=target_expr, is_linear=False, is_convex=False, is_twice_differentiable=False, ) return problem.add_scalarization(scalarization), symbol ``` ### add_iopis_funcs ``` add_iopis_funcs( problem: Problem, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, delta: float = 1e-06, ) -> tuple[Problem, list[str]] ``` Add the IOPIS GUESS and STOM scalarization functions to the problem. Source code in `desdeo/tools/scalarization.py` ``` def add_iopis_funcs( problem: Problem, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, delta: float = 1e-6, ) -> tuple[Problem, list[str]]: """Add the IOPIS GUESS and STOM scalarization functions to the problem.""" symbols = ["iopis_guess", "iopis_stom"] _problem, _ = add_guess_sf_nondiff( problem=problem, symbol=symbols[0], reference_point=reference_point, ideal=ideal, nadir=nadir, rho=rho, ) _problem, _ = add_stom_sf_nondiff( problem=_problem, symbol=symbols[1], reference_point=reference_point, ideal=ideal, delta=delta, ) return _problem, symbols ``` ### add_nimbus_sf_diff ``` add_nimbus_sf_diff( problem: Problem, symbol: str, classifications: dict[str, tuple[str, float | None]], current_objective_vector: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, delta: float = 1e-06, rho: float = 1e-06, ) -> Problem ``` Implements the differentiable variant of the NIMBUS scalarization function. [\\begin{align\*} \\min \\quad & \\alpha + \\rho \\sum\_{i =1}^k \\frac{f_i(\\mathbf{x})}{z_i^{nad} - z_i^{\\star\\star}} \\ \\text{s.t.} \\quad & \\frac{f_i(\\mathbf{x}) - z_i^\*}{z_i^{nad} - z_i^{\\star\\star}} - \\alpha \\leq 0 \\quad & \\forall i \\in I^< \\ & \\frac{f_i(\\mathbf{x}) - \\hat{z}\_i}{z_i^{nad} - z_i^{\\star\\star}} - \\alpha \\leq 0 \\quad & \\forall i \\in I^\\leq \\ & f_i(\\mathbf{x}) - f_i(\\mathbf{x_c}) \\leq 0 \\quad & \\forall i \\in I^< \\cup I^\\leq \\cup I^= \\ & f_i(\\mathbf{x}) - \\epsilon_i \\leq 0 \\quad & \\forall i \\in I^\\geq \\ & \\mathbf{x} \\in S, \\end{align\*}] where (f_i) are objective functions, (f_i(\\mathbf{x_c})) is a component of the current objective function, (\\hat{z}\_i) is an aspiration level, (\\varepsilon_i) is a reservation level, (z_i^\\star) is a component of the ideal point, (z_i^{\\star\\star} = z_i^\\star - \\delta) is a component of the utopian point, (z_i^\\text{nad}) is a component of the nadir point, (\\rho) is a small scalar, (S) is the feasible solution space of the problem (i.e., it means the other constraints of the problem being solved should be accounted for as well), and (\\alpha) is an auxiliary variable. The (I)-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - (I^{\<}): values that should improve, - (I^{\\leq}): values that should improve until a given aspiration level (\\hat{z}\_i), - (I^{=}): values that are fine as they are, - (I^{\\geq}): values that can be impaired until some reservation level (\\varepsilon_i), and - (I^{\\diamond}): values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ``` classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. References Miettinen, K., & Mäkelä, M. M. (2002). On scalarizing functions in multiobjective optimization. OR Spectrum, 24(2), 193-213. Parameters: | Name | Type | Description | Default | | -------------------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to be scalarized. | *required* | | `symbol` | `str` | the symbol given to the scalarization function, i.e., target of the optimization. | *required* | | `classifications` | \`dict\[str, tuple\[str, float | None\]\]\` | a dict, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or None, depending on the classification. See above for an explanation. | | `current_objective_vector` | `dict[str, float]` | the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | a small scalar used to define the utopian point. Defaults to 0.000001. | `1e-06` | | `rho` | `float` | a small scalar used in the augmentation term. Defaults to 0.000001. | `1e-06` | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------- | | `Problem` | tuple\[Problem, str\]: a tuple with a copy of the problem with the added scalarizations and the symbol of the scalarization. | Source code in `desdeo/tools/scalarization.py` ```` def add_nimbus_sf_diff( problem: Problem, symbol: str, classifications: dict[str, tuple[str, float | None]], current_objective_vector: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, delta: float = 0.000001, rho: float = 0.000001, ) -> Problem: r"""Implements the differentiable variant of the NIMBUS scalarization function. \begin{align*} \min \quad & \alpha + \rho \sum_{i =1}^k \frac{f_i(\mathbf{x})}{z_i^{nad} - z_i^{\star\star}} \\ \text{s.t.} \quad & \frac{f_i(\mathbf{x}) - z_i^*}{z_i^{nad} - z_i^{\star\star}} - \alpha \leq 0 \quad & \forall i \in I^< \\ & \frac{f_i(\mathbf{x}) - \hat{z}_i}{z_i^{nad} - z_i^{\star\star}} - \alpha \leq 0 \quad & \forall i \in I^\leq \\ & f_i(\mathbf{x}) - f_i(\mathbf{x_c}) \leq 0 \quad & \forall i \in I^< \cup I^\leq \cup I^= \\ & f_i(\mathbf{x}) - \epsilon_i \leq 0 \quad & \forall i \in I^\geq \\ & \mathbf{x} \in S, \end{align*} where $f_i$ are objective functions, $f_i(\mathbf{x_c})$ is a component of the current objective function, $\hat{z}_i$ is an aspiration level, $\varepsilon_i$ is a reservation level, $z_i^\star$ is a component of the ideal point, $z_i^{\star\star} = z_i^\star - \delta$ is a component of the utopian point, $z_i^\text{nad}$ is a component of the nadir point, $\rho$ is a small scalar, $S$ is the feasible solution space of the problem (i.e., it means the other constraints of the problem being solved should be accounted for as well), and $\alpha$ is an auxiliary variable. The $I$-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - $I^{<}$: values that should improve, - $I^{\leq}$: values that should improve until a given aspiration level $\hat{z}_i$, - $I^{=}$: values that are fine as they are, - $I^{\geq}$: values that can be impaired until some reservation level $\varepsilon_i$, and - $I^{\diamond}$: values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ```python classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. References: Miettinen, K., & Mäkelä, M. M. (2002). On scalarizing functions in multiobjective optimization. OR Spectrum, 24(2), 193-213. Args: problem (Problem): the problem to be scalarized. symbol (str): the symbol given to the scalarization function, i.e., target of the optimization. classifications (dict[str, tuple[str, float | None]]): a dict, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or `None`, depending on the classification. See above for an explanation. current_objective_vector (dict[str, float]): the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): a small scalar used to define the utopian point. Defaults to 0.000001. rho (float, optional): a small scalar used in the augmentation term. Defaults to 0.000001. Returns: tuple[Problem, str]: a tuple with a copy of the problem with the added scalarizations and the symbol of the scalarization. """ # check that classifications have been provided for all objective functions if not objective_dict_has_all_symbols(problem, classifications): msg = ( f"The given classifications {classifications} do not define " "a classification for all the objective functions." ) raise ScalarizationError(msg) # check that at least one objective function is allowed to be improved and one is # allowed to worsen if not any(classifications[obj.symbol][0] in ["<", "<="] for obj in problem.objectives) or not any( classifications[obj.symbol][0] in [">=", "0"] for obj in problem.objectives ): msg = ( f"The given classifications {classifications} should allow at least one objective function value " "to improve and one to worsen." ) raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # define the objective function of the scalarization aug_expr = " + ".join( [ f"{obj.symbol}_min / ({nadir_point[obj.symbol]} - {ideal_point[obj.symbol] - delta})" for obj in problem.objectives ] ) target_expr = f"_alpha + {rho}*" + f"({aug_expr})" scalarization = ScalarizationFunction( name="NIMBUS scalarization objective function", symbol=symbol, func=target_expr, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) constraints = [] # create all the constraints for obj in problem.objectives: _symbol = obj.symbol match classifications[_symbol]: case ("<", _): expr = ( f"({_symbol}_min - {ideal_point[_symbol]}) / " f"({nadir_point[_symbol] - (ideal_point[_symbol] - delta)}) - _alpha" ) constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_lt", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) # if obj is to be maximized, then the current objective vector value needs to be multiplied by -1 expr = f"{_symbol}_min - {current_objective_vector[_symbol]}{' * -1' if obj.maximize else ''}" constraints.append( Constraint( name=f"stay at least equal constraint for {_symbol}", symbol=f"{_symbol}_eq", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("<=", aspiration): # if obj is to be maximized, then the current reservation value needs to be multiplied by -1 expr = ( f"({_symbol}_min - {aspiration}{' * -1' if obj.maximize else ''}) / " f"({nadir_point[_symbol]} - {ideal_point[_symbol] - delta}) - _alpha" ) constraints.append( Constraint( name=f"improvement until constraint for {_symbol}", symbol=f"{_symbol}_lte", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) # if obj is to be maximized, then the current objective vector value needs to be multiplied by -1 expr = f"{_symbol}_min - {current_objective_vector[_symbol]}{' * -1' if obj.maximize else ''}" constraints.append( Constraint( name=f"stay at least equal constraint for {_symbol}", symbol=f"{_symbol}_eq", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("=", _): # if obj is to be maximized, then the current objective vector value needs to be multiplied by -1 expr = f"{_symbol}_min - {current_objective_vector[_symbol]}{' * -1' if obj.maximize else ''}" constraints.append( Constraint( name=f"stay at least equal constraint for {_symbol}", symbol=f"{_symbol}_eq", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case (">=", reservation): # if obj is to be maximized, then the reservation value needs to be multiplied by -1 expr = f"{_symbol}_min - {reservation}{' * -1' if obj.maximize else ''}" constraints.append( Constraint( name=f"worsen until constriant for {_symbol}", symbol=f"{_symbol}_gte", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("0", _): # not relevant for this scalarization pass case (c, _): msg = ( f"Warning! The classification {c} was supplied, but it is not supported." "Must be one of ['<', '<=', '0', '=', '>=']" ) # add the auxiliary variable, scalarization, and constraints _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ```` ### add_nimbus_sf_nondiff ``` add_nimbus_sf_nondiff( problem: Problem, symbol: str, classifications: dict[str, tuple[str, float | None]], current_objective_vector: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, delta: float = 1e-06, rho: float = 1e-06, ) -> Problem ``` Implements the non-differentiable variant of the NIMBUS scalarization function. \[\\begin{align\*} \\underset{\\mathbf{x}}{\\min} \\underset{\\substack{j \\in I^\\leq \\i \\in I^\<}}{\\max} &\\left\[ \\frac{f_i(\\mathbf{x}) - z_i^\\star}{z_i^\\text{nad} - z_i^{\\star\\star}}, \\frac{f_j(\\mathbf{x}) - \\hat{z}_j}{z_j^\\text{nad} - x_j^{\\star\\star}} \\right\] +\\rho \\sum_{i =1}^k \\frac{f_i(\\mathbf{x})}{z_i^{nad} - z_i^{\\star\\star}} \\ \\text{s.t.} \\quad & f_i(\\mathbf{x}) - f_i(\\mathbf{x}^c) \\leq 0\\quad&\\forall i \\in I^< \\cup I^\\leq \\cup I^=,\\ & f_i(\\mathbf{x}) - \\epsilon_i \\leq 0\\quad&\\forall i \\in I^\\geq,\\ & \\mathbf{x} \\in S, \\end{align\*}\] where (f_i) are objective functions, (f_i(\\mathbf{x_c})) is a component of the current objective function, (\\hat{z}\_i) is an aspiration level, (\\varepsilon_i) is a reservation level, (z_i^\\star) is a component of the ideal point, (z_i^{\\star\\star} = z_i^\\star - \\delta) is a component of the utopian point, (z_i^\\text{nad}) is a component of the nadir point, (\\rho) is a small scalar, and (S) is the feasible solution space of the problem (i.e., it means the other constraints of the problem being solved should be accounted for as well). The (I)-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - (I^{\<}): values that should improve, - (I^{\\leq}): values that should improve until a given aspiration level (\\hat{z}\_i), - (I^{=}): values that are fine as they are, - (I^{\\geq}): values that can be impaired until some reservation level (\\varepsilon_i), and - (I^{\\diamond}): values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ``` classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. References Miettinen, K., & Mäkelä, M. M. (2002). On scalarizing functions in multiobjective optimization. OR Spectrum, 24(2), 193-213. Parameters: | Name | Type | Description | Default | | -------------------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to be scalarized. | *required* | | `symbol` | `str` | the symbol given to the scalarization function, i.e., target of the optimization. | *required* | | `classifications` | \`dict\[str, tuple\[str, float | None\]\]\` | a dict, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or None, depending on the classification. See above for an explanation. | | `current_objective_vector` | `dict[str, float]` | the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. | *required* | | `ideal` | `dict[str, float]` | optional ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | optional nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | a small scalar used to define the utopian point. Defaults to 0.000001. | `1e-06` | | `rho` | `float` | a small scalar used in the augmentation term. Defaults to 0.000001. | `1e-06` | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------- | | `Problem` | tuple\[Problem, str\]: a tuple with a copy of the problem with the added scalarizations and the symbol of the scalarization. | Source code in `desdeo/tools/scalarization.py` ```` def add_nimbus_sf_nondiff( problem: Problem, symbol: str, classifications: dict[str, tuple[str, float | None]], current_objective_vector: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, delta: float = 0.000001, rho: float = 0.000001, ) -> Problem: r"""Implements the non-differentiable variant of the NIMBUS scalarization function. \begin{align*} \underset{\mathbf{x}}{\min} \underset{\substack{j \in I^\leq \\i \in I^<}}{\max} &\left[ \frac{f_i(\mathbf{x}) - z_i^\star}{z_i^\text{nad} - z_i^{\star\star}}, \frac{f_j(\mathbf{x}) - \hat{z}_j}{z_j^\text{nad} - x_j^{\star\star}} \right] +\rho \sum_{i =1}^k \frac{f_i(\mathbf{x})}{z_i^{nad} - z_i^{\star\star}} \\ \text{s.t.} \quad & f_i(\mathbf{x}) - f_i(\mathbf{x}^c) \leq 0\quad&\forall i \in I^< \cup I^\leq \cup I^=,\\ & f_i(\mathbf{x}) - \epsilon_i \leq 0\quad&\forall i \in I^\geq,\\ & \mathbf{x} \in S, \end{align*} where $f_i$ are objective functions, $f_i(\mathbf{x_c})$ is a component of the current objective function, $\hat{z}_i$ is an aspiration level, $\varepsilon_i$ is a reservation level, $z_i^\star$ is a component of the ideal point, $z_i^{\star\star} = z_i^\star - \delta$ is a component of the utopian point, $z_i^\text{nad}$ is a component of the nadir point, $\rho$ is a small scalar, and $S$ is the feasible solution space of the problem (i.e., it means the other constraints of the problem being solved should be accounted for as well). The $I$-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - $I^{<}$: values that should improve, - $I^{\leq}$: values that should improve until a given aspiration level $\hat{z}_i$, - $I^{=}$: values that are fine as they are, - $I^{\geq}$: values that can be impaired until some reservation level $\varepsilon_i$, and - $I^{\diamond}$: values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ```python classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. References: Miettinen, K., & Mäkelä, M. M. (2002). On scalarizing functions in multiobjective optimization. OR Spectrum, 24(2), 193-213. Args: problem (Problem): the problem to be scalarized. symbol (str): the symbol given to the scalarization function, i.e., target of the optimization. classifications (dict[str, tuple[str, float | None]]): a dict, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or `None`, depending on the classification. See above for an explanation. current_objective_vector (dict[str, float]): the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. ideal (dict[str, float], optional): optional ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): optional nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): a small scalar used to define the utopian point. Defaults to 0.000001. rho (float, optional): a small scalar used in the augmentation term. Defaults to 0.000001. Returns: tuple[Problem, str]: a tuple with a copy of the problem with the added scalarizations and the symbol of the scalarization. """ # check that classifications have been provided for all objective functions if not objective_dict_has_all_symbols(problem, classifications): msg = ( f"The given classifications {classifications} do not define " "a classification for all the objective functions." ) raise ScalarizationError(msg) # check that at least one objective function is allowed to be improved and one is # allowed to worsen if not any(classifications[obj.symbol][0] in ["<", "<="] for obj in problem.objectives) or not any( classifications[obj.symbol][0] in [">=", "0"] for obj in problem.objectives ): msg = ( f"The given classifications {classifications} should allow at least one objective function value " "to improve and one to worsen." ) raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) corrected_current_point = flip_maximized_objective_values(problem, current_objective_vector) # max term and constraints max_args = [] constraints = [] for obj in problem.objectives: _symbol = obj.symbol match classifications[_symbol]: case ("<", _): max_expr = ( f"({_symbol}_min - {ideal_point[_symbol]}) / " f"({nadir_point[_symbol]} - {ideal_point[_symbol] - delta})" ) max_args.append(max_expr) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("<=", aspiration): # if obj is to be maximized, then the current reservation value needs to be multiplied by -1 max_expr = ( f"({_symbol}_min - {aspiration * -1 if obj.maximize else aspiration}) / " f"({nadir_point[_symbol]} - {ideal_point[_symbol] - delta})" ) max_args.append(max_expr) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement until constraint for {_symbol}", symbol=f"{_symbol}_lte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("=", _): con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"Stay at least as good constraint for {_symbol}", symbol=f"{_symbol}_eq", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case (">=", reservation): con_expr = f"{_symbol}_min - {-1 * reservation if obj.maximize else reservation}" constraints.append( Constraint( name=f"Worsen until constraint for {_symbol}", symbol=f"{_symbol}_gte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("0", _): # not relevant for this scalarization pass case (c, _): msg = ( f"Warning! The classification {c} was supplied, but it is not supported." "Must be one of ['<', '<=', '0', '=', '>=']" ) max_expr = f"Max({','.join(max_args)})" # define the objective function of the scalarization aug_expr = " + ".join( [ f"{obj.symbol}_min / ({nadir_point[obj.symbol]} - {ideal_point[obj.symbol] - delta})" for obj in problem.objectives ] ) target_expr = f"{max_expr} + {rho}*({aug_expr})" scalarization = ScalarizationFunction( name="NIMBUS scalarization objective function", symbol=symbol, func=target_expr, is_linear=False, is_convex=False, is_twice_differentiable=False, ) _problem = problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ```` ### add_objective_as_scalarization ``` add_objective_as_scalarization( problem: Problem, symbol: str, objective_symbol: str ) -> tuple[Problem, str] ``` Creates a scalarization where one of the problem's objective functions is optimized. The scalarization is defined as follows: [\\begin{equation} \\operatorname{min}\_{\\mathbf{x} \\in S} f_t(\\mathbf{x}), \\end{equation}] where (f_t(\\mathbf{x})) is the objective function to be minimized. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | --------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to which the scalarization should be added. | *required* | | `symbol` | `str` | the symbol to reference the added scalarization function. | *required* | | `objective_symbol` | `str` | the symbol of the objective function to be optimized. | *required* | Raises: | Type | Description | | -------------------- | --------------------------------------------------------- | | `ScalarizationError` | the given objective_symbol does not exist in the problem. | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/scalarization.py` ``` def add_objective_as_scalarization(problem: Problem, symbol: str, objective_symbol: str) -> tuple[Problem, str]: r"""Creates a scalarization where one of the problem's objective functions is optimized. The scalarization is defined as follows: \begin{equation} \operatorname{min}_{\mathbf{x} \in S} f_t(\mathbf{x}), \end{equation} where $f_t(\mathbf{x})$ is the objective function to be minimized. Args: problem (Problem): the problem to which the scalarization should be added. symbol (str): the symbol to reference the added scalarization function. objective_symbol (str): the symbol of the objective function to be optimized. Raises: ScalarizationError: the given objective_symbol does not exist in the problem. Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ # check that symbol exists if problem.get_objective(objective_symbol, copy=False) is None: msg = f"The given objective symbol {objective_symbol} is not defined in the problem.." raise ScalarizationError(msg) sf = ["Multiply", 1, f"{objective_symbol}_min"] original_objective = problem.get_objective(objective_symbol, copy=False) # Add the function to the problem scalarization_function = ScalarizationFunction( name=f"Objective {objective_symbol}", symbol=symbol, func=sf, is_linear=original_objective.is_linear, is_convex=original_objective.is_convex, is_twice_differentiable=original_objective.is_twice_differentiable, ) return problem.add_scalarization(scalarization_function), symbol ``` ### add_stom_sf_diff ``` add_stom_sf_diff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, rho: float = 1e-06, delta: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the differentiable variant of the STOM scalarizing function. \[\\begin{align\*} \\min \\quad & \\alpha + \\rho \\sum\_{i=1}^k \\frac{f_i(\\mathbf{x})}{\\bar{z}\_i - z_i^{\\star\\star}} \\ \\text{s.t.} \\quad & \\frac{f_i(\\mathbf{x}) - z_i^{\\star\\star}}{\\bar{z}\_i - z_i^{\\star\\star}} - \\alpha \\leq 0 \\quad & \\forall i = 1,\\dots,k\\ & \\mathbf{x} \\in S, \\end{align\*}\] where (f_i) are objective functions, (z_i^{\\star\\star} = z_i^\\star - \\delta) is a component of the utopian point, (\\bar{z}\_i) is a component of the reference point, (\\rho) and (\\delta) are small scalar values, (S) is the feasible solution space of the original problem, and (\\alpha) is an auxiliary variable. References H. Nakayama, Y. Sawaragi, Satisficing trade-off method for multiobjective programming, in: M. Grauer, A.P. Wierzbicki (Eds.), Interactive Decision Analysis, Springer Verlag, Berlin, 1984, pp. 113-122. Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_point` | `dict[str, float]` | a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar value to define the utopian point. Defaults to 1e-6. | `1e-06` | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/scalarization.py` ``` def add_stom_sf_diff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, rho: float = 1e-6, delta: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the differentiable variant of the STOM scalarizing function. \begin{align*} \min \quad & \alpha + \rho \sum_{i=1}^k \frac{f_i(\mathbf{x})}{\bar{z}_i - z_i^{\star\star}} \\ \text{s.t.} \quad & \frac{f_i(\mathbf{x}) - z_i^{\star\star}}{\bar{z}_i - z_i^{\star\star}} - \alpha \leq 0 \quad & \forall i = 1,\dots,k\\ & \mathbf{x} \in S, \end{align*} where $f_i$ are objective functions, $z_i^{\star\star} = z_i^\star - \delta$ is a component of the utopian point, $\bar{z}_i$ is a component of the reference point, $\rho$ and $\delta$ are small scalar values, $S$ is the feasible solution space of the original problem, and $\alpha$ is an auxiliary variable. References: H. Nakayama, Y. Sawaragi, Satisficing trade-off method for multiobjective programming, in: M. Grauer, A.P. Wierzbicki (Eds.), Interactive Decision Analysis, Springer Verlag, Berlin, 1984, pp. 113-122. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_point (dict[str, float]): a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar value to define the utopian point. Defaults to 1e-6. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check reference point if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing value for one or more objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) corrected_rp = flip_maximized_objective_values(problem, reference_point) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # define the objective function of the scalarization aug_expr = " + ".join( [ f"{obj.symbol}_min / ({(corrected_rp[obj.symbol] - ideal_point[obj.symbol]) + delta})" for obj in problem.objectives ] ) target_expr = f"_alpha + {rho}*" + f"({aug_expr})" scalarization = ScalarizationFunction( name="STOM scalarization objective function", symbol=symbol, func=target_expr, is_twice_differentiable=problem.is_twice_differentiable, is_linear=problem.is_linear, is_convex=problem.is_convex, ) constraints = [] for obj in problem.objectives: expr = ( f"({obj.symbol}_min - {ideal_point[obj.symbol] - delta}) / " f"({(corrected_rp[obj.symbol] - ideal_point[obj.symbol]) + delta}) - _alpha" ) constraints.append( Constraint( name=f"Max constraint for {obj.symbol}", symbol=f"{obj.symbol}_maxcon", func=expr, cons_type=ConstraintTypeEnum.LTE, is_twice_differentiable=obj.is_twice_differentiable, is_linear=obj.is_linear, is_convex=obj.is_convex, ) ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_stom_sf_nondiff ``` add_stom_sf_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, rho: float = 1e-06, delta: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the non-differentiable variant of the STOM scalarizing function. \[\\begin{align\*} \\underset{\\mathbf{x}}{\\min} \\quad & \\underset{i=1,\\dots,k}{\\max}\\left[ \\frac{f_i(\\mathbf{x}) - z_i^{\\star\\star}}{\\bar{z}\_i - z_i^{\\star\\star}} \\right] - \\rho \\sum\_{i=1}^k \\frac{f_i(\\mathbf{x})}{\\bar{z}\_i - z_i^{\\star\\star}} \\ \\text{s.t.}\\quad & \\mathbf{x} \\in S, \\end{align\*}\] where (f_i) are objective functions, (z_i^{\\star\\star} = z_i^\\star - \\delta) is a component of the utopian point, (\\bar{z}\_i) is a component of the reference point, (\\rho) and (\\delta) are small scalar values, and (S) is the feasible solution space of the original problem. References H. Nakayama, Y. Sawaragi, Satisficing trade-off method for multiobjective programming, in: M. Grauer, A.P. Wierzbicki (Eds.), Interactive Decision Analysis, Springer Verlag, Berlin, 1984, pp. 113-122. Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_point` | `dict[str, float]` | a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar value to define the utopian point. Defaults to 1e-6. | `1e-06` | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/scalarization.py` ``` def add_stom_sf_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, rho: float = 1e-6, delta: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the non-differentiable variant of the STOM scalarizing function. \begin{align*} \underset{\mathbf{x}}{\min} \quad & \underset{i=1,\dots,k}{\max}\left[ \frac{f_i(\mathbf{x}) - z_i^{\star\star}}{\bar{z}_i - z_i^{\star\star}} \right] + \rho \sum_{i=1}^k \frac{f_i(\mathbf{x})}{\bar{z}_i - z_i^{\star\star}} \\ \text{s.t.}\quad & \mathbf{x} \in S, \end{align*} where $f_i$ are objective functions, $z_i^{\star\star} = z_i^\star - \delta$ is a component of the utopian point, $\bar{z}_i$ is a component of the reference point, $\rho$ and $\delta$ are small scalar values, and $S$ is the feasible solution space of the original problem. References: H. Nakayama, Y. Sawaragi, Satisficing trade-off method for multiobjective programming, in: M. Grauer, A.P. Wierzbicki (Eds.), Interactive Decision Analysis, Springer Verlag, Berlin, 1984, pp. 113-122. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_point (dict[str, float]): a dict with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar value to define the utopian point. Defaults to 1e-6. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check reference point if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing value for one or more objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) corrected_rp = flip_maximized_objective_values(problem, reference_point) # define the objective function of the scalarization max_expr = ", ".join( [ ( f"({obj.symbol}_min - {ideal_point[obj.symbol] - delta}) / " f"({(corrected_rp[obj.symbol] - ideal_point[obj.symbol]) + delta})" ) for obj in problem.objectives ] ) aug_expr = " + ".join( [ f"{obj.symbol}_min / ({(corrected_rp[obj.symbol] - ideal_point[obj.symbol]) + delta})" for obj in problem.objectives ] ) target_expr = f"{Op.MAX}({max_expr}) + {rho}*" + f"({aug_expr})" scalarization = ScalarizationFunction( name="STOM scalarization objective function", symbol=symbol, func=target_expr, is_linear=False, is_convex=False, is_twice_differentiable=False, ) return problem.add_scalarization(scalarization), symbol ``` ### add_weighted_sums ``` add_weighted_sums( problem: Problem, symbol: str, weights: dict[str, float] ) -> tuple[Problem, str] ``` Add the weighted sums scalarization to a problem with the given weights. It is assumed that the weights add to 1. The scalarization is defined as follows: \[\\begin{equation} \\begin{aligned} & \\mathcal{S}_\\text{WS}(F(\\mathbf{x});\\mathbf{w}) = \\sum_{i=1}^{k} w_i f_i(\\mathbf{x}) \\ & \\text{s.t.} \\sum\_{i=1}^{k} w_i = 1, \\end{aligned} \\end{equation}\] where (\\mathbf{w} = [w_1,\\dots,w_k]) are the weights and (k) is the number of objective functions. Warning The weighted sums scalarization is often not capable of finding most Pareto optimal solutions when optimized. It is advised to utilize some better scalarization functions. Parameters: | Name | Type | Description | Default | | --------- | ------------------ | ------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to which the scalarization should be added. | *required* | | `symbol` | `str` | the symbol to reference the added scalarization function. | *required* | | `weights` | `dict[str, float]` | the weights. For the method to work, the weights should sum to 1. However, this is not a condition that is checked. | *required* | Raises: | Type | Description | | -------------------- | ----------------------------------------------------------- | | `ScalarizationError` | if the weights are missing any of the objective components. | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/scalarization.py` ``` def add_weighted_sums(problem: Problem, symbol: str, weights: dict[str, float]) -> tuple[Problem, str]: r"""Add the weighted sums scalarization to a problem with the given weights. It is assumed that the weights add to 1. The scalarization is defined as follows: \begin{equation} \begin{aligned} & \mathcal{S}_\text{WS}(F(\mathbf{x});\mathbf{w}) = \sum_{i=1}^{k} w_i f_i(\mathbf{x}) \\ & \text{s.t.} \sum_{i=1}^{k} w_i = 1, \end{aligned} \end{equation} where $\mathbf{w} = [w_1,\dots,w_k]$ are the weights and $k$ is the number of objective functions. Warning: The weighted sums scalarization is often not capable of finding most Pareto optimal solutions when optimized. It is advised to utilize some better scalarization functions. Args: problem (Problem): the problem to which the scalarization should be added. symbol (str): the symbol to reference the added scalarization function. weights (dict[str, float]): the weights. For the method to work, the weights should sum to 1. However, this is not a condition that is checked. Raises: ScalarizationError: if the weights are missing any of the objective components. Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ # check that the weights have all the objective components if not all(obj.symbol in weights for obj in problem.objectives): msg = f"The given weight vector {weights} does not have a component defined for all the objectives." raise ScalarizationError(msg) # Build the sum sum_terms = [f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives] # aggregate the terms sf = " + ".join(sum_terms) # Add the function to the problem scalarization_function = ScalarizationFunction( name="Weighted sums scalarization function", symbol=symbol, func=sf, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) return problem.add_scalarization(scalarization_function), symbol ``` ### create_epsilon_constraints_json ``` create_epsilon_constraints_json( problem: Problem, objective_symbol: str, epsilons: dict[str, float], ) -> tuple[list[str | int | float], list[str]] ``` Creates JSON expressions for an epsilon constraints scalarization and constraints. It is assumed that epsilon have been given in a format where each objective is to be minimized. Warning To be deprecated. Parameters: | Name | Type | Description | Default | | ------------------ | ------------------ | ---------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to scalarize. | *required* | | `objective_symbol` | `str` | the objective used as the objective in the epsilon constraint scalarization. | *required* | | `epsilons` | `dict[str, float]` | the epsilon constraint values in a dict with each key being an objective's symbol. | *required* | Raises: | Type | Description | | -------------------- | ------------------------------------------------- | | `ScalarizationError` | objective_symbol not found in problem definition. | Returns: | Type | Description | | ------------------ | ----------- | | \`tuple\[list\[str | int | Source code in `desdeo/tools/scalarization.py` ``` def create_epsilon_constraints_json( problem: Problem, objective_symbol: str, epsilons: dict[str, float] ) -> tuple[list[str | int | float], list[str]]: """Creates JSON expressions for an epsilon constraints scalarization and constraints. It is assumed that epsilon have been given in a format where each objective is to be minimized. Warning: To be deprecated. Args: problem (Problem): the problem to scalarize. objective_symbol (str): the objective used as the objective in the epsilon constraint scalarization. epsilons (dict[str, float]): the epsilon constraint values in a dict with each key being an objective's symbol. Raises: ScalarizationError: `objective_symbol` not found in problem definition. Returns: tuple[list, list]: the first element is the expression of the scalarized objective expressed in MathJSON format. The second element is a list of expressions of the constraints expressed in MathJSON format. The constraints are in less than or equal format. """ correct_symbols = [objective.symbol for objective in problem.objectives] if objective_symbol not in correct_symbols: msg = f"The given objective symbol {objective_symbol} should be one of {correct_symbols}." raise ScalarizationError(msg) correct_symbols.remove(objective_symbol) scalarization_expr = ["Multiply", 1, f"{objective_symbol}_min"] # the epsilons must be given such that each objective function is to be minimized constraint_exprs = [["Add", f"{obj}_min", ["Negate", epsilons[obj]]] for obj in correct_symbols] return scalarization_expr, constraint_exprs ``` ### objective_dict_has_all_symbols ``` objective_dict_has_all_symbols( problem: Problem, obj_dict: dict[str, float] ) -> bool ``` Check that a dict has all the objective function symbols of a problem as its keys. Parameters: | Name | Type | Description | Default | | ---------- | ------------------ | -------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem with the objective symbols. | *required* | | `obj_dict` | `dict[str, float]` | a dict that should have a key for each objective symbol. | *required* | Returns: | Name | Type | Description | | ------ | ------ | ------------------------------------------- | | `bool` | `bool` | whether all the symbols are present or not. | Source code in `desdeo/tools/scalarization.py` ``` def objective_dict_has_all_symbols(problem: Problem, obj_dict: dict[str, float]) -> bool: """Check that a dict has all the objective function symbols of a problem as its keys. Args: problem (Problem): the problem with the objective symbols. obj_dict (dict[str, float]): a dict that should have a key for each objective symbol. Returns: bool: whether all the symbols are present or not. """ return all(obj.symbol in obj_dict for obj in problem.objectives) ``` ## Partial scalarization Scalarization functions that operate on a subset of the problem's objectives. ### \_build_aug_expr ``` _build_aug_expr( weights_aug: dict[str, float] | None, active_objectives: list, default_weights: dict[str, float], all_objectives: list, corrected_rp_aug: dict[str, float] | None, ) -> str ``` Build the augmentation sum expression string. Source code in `desdeo/tools/partial_scalarization.py` ``` def _build_aug_expr( weights_aug: dict[str, float] | None, active_objectives: list, default_weights: dict[str, float], all_objectives: list, corrected_rp_aug: dict[str, float] | None, ) -> str: """Build the augmentation sum expression string.""" if weights_aug is not None: objectives = [obj for obj in all_objectives if obj.symbol in weights_aug and weights_aug[obj.symbol] != 0] weights = weights_aug else: objectives = active_objectives weights = default_weights if not objectives: return "0" terms = [] for obj in objectives: w = weights[obj.symbol] obj_term = f"(-1 * {obj.symbol})" if obj.maximize else obj.symbol if corrected_rp_aug is not None and obj.symbol in corrected_rp_aug: terms.append(f"({obj_term} - {corrected_rp_aug[obj.symbol]}) / ({w})") else: terms.append(f"({obj_term}) / ({w})") return " + ".join(terms) ``` ### add_asf_partial_diff ``` add_asf_partial_diff( problem: Problem, symbol: str, reference_point: dict[str, float], weights: dict[str, float] | None = None, reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, rho: float = 0.001, ) -> tuple[Problem, str] ``` Adds a differentiable generic ASF that scalarizes only the objectives in `reference_point`. This is the partial version of `add_asf_generic_diff`. The subset of objectives to scalarize is determined by the keys of `reference_point`; objectives not present in `reference_point` are left out of both the max-term constraints and the augmentation sum. [\\begin{align\*} \\min \\quad & \\alpha + \\rho \\sum\_{i \\in I} \\frac{f_i(\\mathbf{x})}{w_i} \\ \\text{s.t.} \\quad & \\frac{f_i(\\mathbf{x}) - q_i}{w_i} - \\alpha \\leq 0, \\quad i \\in I,\\ & \\mathbf{x} \\in S, \\end{align\*}] where (I) is the index set of objectives whose symbols appear in `reference_point`, (q_i) are the corresponding aspiration levels, and (w_i) are the weights. When `weights` is `None` the weights default to `nadir_i - ideal_i` (in the minimization-corrected space) for each active objective. In that case every active objective must have both `ideal` and `nadir` defined on its `Objective` instance, otherwise a `ScalarizationError` is raised. Parameters: | Name | Type | Description | Default | | --------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization function. | *required* | | `reference_point` | `dict[str, float]` | maps objective symbols to aspiration levels. Only objectives whose symbols appear here are included in the scalarization. | *required* | | `weights` | \`dict[str, float] | None\` | maps the same objective symbols to positive weight values. If None, defaults to nadir - ideal for each active objective (or 1.0 if ideal equals nadir). | | `reference_point_aug` | \`dict[str, float] | None\` | optional separate reference point for the augmentation term. Must cover the same subset as reference_point when provided. | | `weights_aug` | \`dict[str, float] | None\` | optional separate weights for the augmentation term, must be positive. The augmentation term sign-flips maximized objectives internally, so unlike the pre-correction f_i values these weights should never be negative. Must cover the same subset as reference_point when provided. | | `rho` | `float` | small scalar multiplier for the augmentation sum. Defaults to 1e-6. | `0.001` | Returns: | Type | Description | | --------------------- | ------------------------------------------------------------------------- | | `tuple[Problem, str]` | A tuple of the updated Problem and the symbol of the added scalarization. | Raises: | Type | Description | | -------------------- | ------------------------------------------------------------------------------------------------------- | | `ScalarizationError` | if any key in reference_point is not a valid objective symbol in the problem. | | `ScalarizationError` | if weights is provided but does not cover all active objectives. | | `ScalarizationError` | if weights is provided and contains a non-positive value for an active objective. | | `ScalarizationError` | if weights is None and any active objective is missing an ideal or nadir value. | | `ScalarizationError` | if reference_point_aug or weights_aug are provided but do not cover the same subset as reference_point. | Source code in `desdeo/tools/partial_scalarization.py` ``` def add_asf_partial_diff( problem: Problem, symbol: str, reference_point: dict[str, float], weights: dict[str, float] | None = None, reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, rho: float = 1e-3, ) -> tuple[Problem, str]: r"""Adds a differentiable generic ASF that scalarizes only the objectives in ``reference_point``. This is the partial version of `add_asf_generic_diff`. The subset of objectives to scalarize is determined by the keys of ``reference_point``; objectives not present in ``reference_point`` are left out of both the max-term constraints and the augmentation sum. \begin{align*} \min \quad & \alpha + \rho \sum_{i \in I} \frac{f_i(\mathbf{x})}{w_i} \\ \text{s.t.} \quad & \frac{f_i(\mathbf{x}) - q_i}{w_i} - \alpha \leq 0, \quad i \in I,\\ & \mathbf{x} \in S, \end{align*} where $I$ is the index set of objectives whose symbols appear in ``reference_point``, $q_i$ are the corresponding aspiration levels, and $w_i$ are the weights. When ``weights`` is ``None`` the weights default to ``nadir_i - ideal_i`` (in the minimization-corrected space) for each active objective. In that case every active objective must have both ``ideal`` and ``nadir`` defined on its ``Objective`` instance, otherwise a `ScalarizationError` is raised. Args: problem: the problem the scalarization is added to. symbol: the symbol given to the added scalarization function. reference_point: maps objective symbols to aspiration levels. Only objectives whose symbols appear here are included in the scalarization. weights: maps the same objective symbols to positive weight values. If ``None``, defaults to ``nadir - ideal`` for each active objective (or ``1.0`` if ``ideal`` equals ``nadir``). reference_point_aug: optional separate reference point for the augmentation term. Must cover the same subset as ``reference_point`` when provided. weights_aug: optional separate weights for the augmentation term, must be positive. The augmentation term sign-flips maximized objectives internally, so unlike the pre-correction ``f_i`` values these weights should never be negative. Must cover the same subset as ``reference_point`` when provided. rho: small scalar multiplier for the augmentation sum. Defaults to 1e-6. Returns: A tuple of the updated Problem and the symbol of the added scalarization. Raises: ScalarizationError: if any key in ``reference_point`` is not a valid objective symbol in the problem. ScalarizationError: if ``weights`` is provided but does not cover all active objectives. ScalarizationError: if ``weights`` is provided and contains a non-positive value for an active objective. ScalarizationError: if ``weights`` is ``None`` and any active objective is missing an ``ideal`` or ``nadir`` value. ScalarizationError: if ``reference_point_aug`` or ``weights_aug`` are provided but do not cover the same subset as ``reference_point``. """ active_objectives, effective_weights, corrected_rp, corrected_rp_aug = _resolve_partial_asf_params( problem, reference_point, weights, reference_point_aug, weights_aug ) alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) aug_expr = _build_aug_expr( weights_aug, active_objectives, effective_weights, list(problem.objectives), corrected_rp_aug ) target_expr = f"_alpha + {rho}*({aug_expr})" scalarization = ScalarizationFunction( name="Partial generic ASF scalarization", symbol=symbol, func=target_expr, is_convex=problem.is_convex, is_linear=problem.is_linear, is_twice_differentiable=problem.is_twice_differentiable, ) constraints = [] for obj in active_objectives: obj_term = f"(-1 * {obj.symbol})" if obj.maximize else obj.symbol expr = f"({obj_term} - {corrected_rp[obj.symbol]}) / {effective_weights[obj.symbol]} - _alpha" constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_asf_partial_nondiff ``` add_asf_partial_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], weights: dict[str, float] | None = None, reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds a non-differentiable partial ASF that scalarizes only the objectives in `reference_point`. This is the non-differentiable counterpart of `add_asf_partial_diff`. The max operator is expressed directly in the objective function rather than being linearised with an auxiliary variable and constraints, making the scalarization non-differentiable. \[\\begin{align\*} \\min \\quad & \\underset{i \\in I}{\\max} \\left[\\frac{f_i(\\mathbf{x}) - q_i}{w_i}\\right] - \\rho \\sum\_{i \\in I} \\frac{f_i(\\mathbf{x})}{w_i} \\end{align\*}\] where (I) is the index set of objectives whose symbols appear in `reference_point`, (q_i) are the corresponding aspiration levels, and (w_i) are the weights. When `reference_point_aug` is provided the augmentation numerator becomes (f_i(\\mathbf{x}) - q_i^{\\text{aug}}). Parameters: | Name | Type | Description | Default | | --------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization function. | *required* | | `reference_point` | `dict[str, float]` | maps objective symbols to aspiration levels. Only objectives whose symbols appear here are included in the scalarization. | *required* | | `weights` | \`dict[str, float] | None\` | maps the same objective symbols to positive weight values. If None, defaults to nadir - ideal for each active objective (or 1.0 if ideal equals nadir). | | `reference_point_aug` | \`dict[str, float] | None\` | optional separate reference point for the augmentation term. Must cover the same subset as reference_point when provided. | | `weights_aug` | \`dict[str, float] | None\` | optional separate weights for the augmentation term, must be positive. The augmentation term sign-flips maximized objectives internally, so unlike the pre-correction f_i values these weights should never be negative. Must cover the same subset as reference_point when provided. | | `rho` | `float` | small scalar multiplier for the augmentation sum. Defaults to 1e-6. | `1e-06` | Returns: | Type | Description | | --------------------- | ------------------------------------------------------------------------- | | `tuple[Problem, str]` | A tuple of the updated Problem and the symbol of the added scalarization. | Raises: | Type | Description | | -------------------- | ------------------------------------------------------------------------------------------------------- | | `ScalarizationError` | if any key in reference_point is not a valid objective symbol. | | `ScalarizationError` | if weights is provided but does not cover all active objectives. | | `ScalarizationError` | if weights is provided and contains a non-positive value for an active objective. | | `ScalarizationError` | if weights is None and any active objective is missing an ideal or nadir value. | | `ScalarizationError` | if reference_point_aug or weights_aug are provided but do not cover the same subset as reference_point. | Source code in `desdeo/tools/partial_scalarization.py` ``` def add_asf_partial_nondiff( problem: Problem, symbol: str, reference_point: dict[str, float], weights: dict[str, float] | None = None, reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds a non-differentiable partial ASF that scalarizes only the objectives in ``reference_point``. This is the non-differentiable counterpart of `add_asf_partial_diff`. The max operator is expressed directly in the objective function rather than being linearised with an auxiliary variable and constraints, making the scalarization non-differentiable. \begin{align*} \min \quad & \underset{i \in I}{\max} \left[\frac{f_i(\mathbf{x}) - q_i}{w_i}\right] + \rho \sum_{i \in I} \frac{f_i(\mathbf{x})}{w_i} \end{align*} where $I$ is the index set of objectives whose symbols appear in ``reference_point``, $q_i$ are the corresponding aspiration levels, and $w_i$ are the weights. When ``reference_point_aug`` is provided the augmentation numerator becomes $f_i(\mathbf{x}) - q_i^{\text{aug}}$. Args: problem: the problem the scalarization is added to. symbol: the symbol given to the added scalarization function. reference_point: maps objective symbols to aspiration levels. Only objectives whose symbols appear here are included in the scalarization. weights: maps the same objective symbols to positive weight values. If ``None``, defaults to ``nadir - ideal`` for each active objective (or ``1.0`` if ``ideal`` equals ``nadir``). reference_point_aug: optional separate reference point for the augmentation term. Must cover the same subset as ``reference_point`` when provided. weights_aug: optional separate weights for the augmentation term, must be positive. The augmentation term sign-flips maximized objectives internally, so unlike the pre-correction ``f_i`` values these weights should never be negative. Must cover the same subset as ``reference_point`` when provided. rho: small scalar multiplier for the augmentation sum. Defaults to 1e-6. Returns: A tuple of the updated Problem and the symbol of the added scalarization. Raises: ScalarizationError: if any key in ``reference_point`` is not a valid objective symbol. ScalarizationError: if ``weights`` is provided but does not cover all active objectives. ScalarizationError: if ``weights`` is provided and contains a non-positive value for an active objective. ScalarizationError: if ``weights`` is ``None`` and any active objective is missing an ``ideal`` or ``nadir`` value. ScalarizationError: if ``reference_point_aug`` or ``weights_aug`` are provided but do not cover the same subset as ``reference_point``. """ active_objectives, effective_weights, corrected_rp, corrected_rp_aug = _resolve_partial_asf_params( problem, reference_point, weights, reference_point_aug, weights_aug ) # Build the max term over active objectives only. max_operands = [] for obj in active_objectives: obj_term = f"(-1 * {obj.symbol})" if obj.maximize else obj.symbol max_operands.append(f"({obj_term} - {corrected_rp[obj.symbol]}) / ({effective_weights[obj.symbol]})") max_term = f"{Op.MAX}({', '.join(max_operands)})" aug_expr = _build_aug_expr( weights_aug, active_objectives, effective_weights, list(problem.objectives), corrected_rp_aug ) sf = f"{max_term} + {rho} * ({aug_expr})" scalarization = ScalarizationFunction( name="Partial non-differentiable ASF scalarization", symbol=symbol, func=sf, is_linear=False, is_convex=False, is_twice_differentiable=False, ) return problem.add_scalarization(scalarization), symbol ``` ### add_cumulonimbus_diff ``` add_cumulonimbus_diff( problem: Problem, symbol: str, classifications: dict[str, tuple[str, float | None]], current_objective_vector: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, delta: float = 1e-06, rho: float = 0.001, ) -> tuple[Problem, str] ``` Adds a differentiable partial NIMBUS scalarization that only covers classified objectives. This is the partial variant of `add_nimbus_sf_diff`. Unlike the full NIMBUS scalarization, `classifications` does not need to cover every objective in the problem — objectives whose symbols are absent from `classifications` are left unconstrained (treated as free, equivalent to the `"0"` class). [\\begin{align\*} \\min \\quad & \\alpha + \\rho \\sum\_{i \\in I} \\frac{f_i(\\mathbf{x}) - q_i^{\\text{aug}}}{w_i^{\\text{aug}}} \\ \\text{s.t.} \\quad & \\frac{f_i(\\mathbf{x}) - z_i^\\star}{z_i^{\\text{nad}} - z_i^{\\star\\star}} - \\alpha \\leq 0 & \\forall i \\in I^< \\ & \\frac{f_i(\\mathbf{x}) - \\hat{z}\_i}{z_i^{\\text{nad}} - z_i^{\\star\\star}} - \\alpha \\leq 0 & \\forall i \\in I^\\leq \\ & f_i(\\mathbf{x}) - f_i(\\mathbf{x_c}) \\leq 0 & \\forall i \\in I^< \\cup I^\\leq \\cup I^= \\ & f_i(\\mathbf{x}) - \\varepsilon_i \\leq 0 & \\forall i \\in I^\\geq \\ & \\mathbf{x} \\in S, \\end{align\*}] where (I) is the index set of classified objectives (keys of `classifications`), (z_i^{\\star\\star} = z_i^\\star - \\delta) is the utopian point component, (w_i^{\\text{aug}}) are the augmentation weights (defaulting to (z_i^{\\text{nad}} - z_i^{\\star\\star})), (q_i^{\\text{aug}}) is the optional augmentation reference point (omitted when not provided), and all other notation follows `add_nimbus_sf_diff`. Parameters: | Name | Type | Description | Default | | -------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to be scalarized. | *required* | | `symbol` | `str` | the symbol given to the added scalarization function. | *required* | | `classifications` | \`dict\[str, tuple\[str, float | None\]\]\` | maps objective symbols to (class, level) tuples. Only objectives listed here participate in the scalarization; others are free. Valid classes: "\<", "\<=", "=", ">=" (with a level), "0". | | `current_objective_vector` | `dict[str, float]` | current objective values needed for \<, \<=, and = constraints. Must contain entries for every objective classified as "\<", "\<=", or "=". | *required* | | `ideal` | \`dict[str, float] | None\` | ideal point override. If None, derived from problem. | | `nadir` | \`dict[str, float] | None\` | nadir point override. If None, derived from problem. | | `reference_point_aug` | \`dict[str, float] | None\` | optional reference point for the augmentation term. When provided, each augmentation term becomes (f_i - q_i^aug) / w_i^aug instead of f_i / w_i^aug. Must cover every objective present in classifications. | | `weights_aug` | \`dict[str, float] | None\` | optional weights for the augmentation term, must be positive. Replaces the default nadir - utopian weights. The augmentation term sign-flips maximized objectives internally, so these weights should never be negative. Must cover every objective present in classifications. | | `delta` | `float` | small scalar for the utopian offset. Defaults to 1e-6. | `1e-06` | | `rho` | `float` | small scalar for the augmentation term. Defaults to 1e-3. | `0.001` | Returns: | Type | Description | | --------------------- | ------------------------------------------------------------------------- | | `tuple[Problem, str]` | A tuple of the updated Problem and the symbol of the added scalarization. | Raises: | Type | Description | | -------------------- | -------------------------------------------------------------------------------------------------------------- | | `ScalarizationError` | if any key in classifications is not a valid objective symbol. | | `ScalarizationError` | if an objective classified as "\<", "\<=", or "=" is missing from current_objective_vector. | | `ScalarizationError` | if ideal or nadir cannot be determined for an active objective. | | `ScalarizationError` | if reference_point_aug or weights_aug are provided but do not cover all objectives present in classifications. | Source code in `desdeo/tools/partial_scalarization.py` ``` def add_cumulonimbus_diff( problem: Problem, symbol: str, classifications: dict[str, tuple[str, float | None]], current_objective_vector: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, reference_point_aug: dict[str, float] | None = None, weights_aug: dict[str, float] | None = None, delta: float = 1e-6, rho: float = 1e-3, ) -> tuple[Problem, str]: r"""Adds a differentiable partial NIMBUS scalarization that only covers classified objectives. This is the partial variant of `add_nimbus_sf_diff`. Unlike the full NIMBUS scalarization, ``classifications`` does not need to cover every objective in the problem — objectives whose symbols are absent from ``classifications`` are left unconstrained (treated as free, equivalent to the ``"0"`` class). \begin{align*} \min \quad & \alpha + \rho \sum_{i \in I} \frac{f_i(\mathbf{x}) - q_i^{\text{aug}}}{w_i^{\text{aug}}} \\ \text{s.t.} \quad & \frac{f_i(\mathbf{x}) - z_i^\star}{z_i^{\text{nad}} - z_i^{\star\star}} - \alpha \leq 0 & \forall i \in I^< \\ & \frac{f_i(\mathbf{x}) - \hat{z}_i}{z_i^{\text{nad}} - z_i^{\star\star}} - \alpha \leq 0 & \forall i \in I^\leq \\ & f_i(\mathbf{x}) - f_i(\mathbf{x_c}) \leq 0 & \forall i \in I^< \cup I^\leq \cup I^= \\ & f_i(\mathbf{x}) - \varepsilon_i \leq 0 & \forall i \in I^\geq \\ & \mathbf{x} \in S, \end{align*} where $I$ is the index set of classified objectives (keys of ``classifications``), $z_i^{\star\star} = z_i^\star - \delta$ is the utopian point component, $w_i^{\text{aug}}$ are the augmentation weights (defaulting to $z_i^{\text{nad}} - z_i^{\star\star}$), $q_i^{\text{aug}}$ is the optional augmentation reference point (omitted when not provided), and all other notation follows `add_nimbus_sf_diff`. Args: problem: the problem to be scalarized. symbol: the symbol given to the added scalarization function. classifications: maps objective symbols to ``(class, level)`` tuples. Only objectives listed here participate in the scalarization; others are free. Valid classes: ``"<"``, ``"<="``, ``"="``, ``">="`` (with a level), ``"0"``. current_objective_vector: current objective values needed for ``<``, ``<=``, and ``=`` constraints. Must contain entries for every objective classified as ``"<"``, ``"<="``, or ``"="``. ideal: ideal point override. If ``None``, derived from ``problem``. nadir: nadir point override. If ``None``, derived from ``problem``. reference_point_aug: optional reference point for the augmentation term. When provided, each augmentation term becomes ``(f_i - q_i^aug) / w_i^aug`` instead of ``f_i / w_i^aug``. Must cover every objective present in ``classifications``. weights_aug: optional weights for the augmentation term, must be positive. Replaces the default ``nadir - utopian`` weights. The augmentation term sign-flips maximized objectives internally, so these weights should never be negative. Must cover every objective present in ``classifications``. delta: small scalar for the utopian offset. Defaults to 1e-6. rho: small scalar for the augmentation term. Defaults to 1e-3. Returns: A tuple of the updated Problem and the symbol of the added scalarization. Raises: ScalarizationError: if any key in ``classifications`` is not a valid objective symbol. ScalarizationError: if an objective classified as ``"<"``, ``"<="``, or ``"="`` is missing from ``current_objective_vector``. ScalarizationError: if ideal or nadir cannot be determined for an active objective. ScalarizationError: if ``reference_point_aug`` or ``weights_aug`` are provided but do not cover all objectives present in ``classifications``. """ valid_symbols = {obj.symbol for obj in problem.objectives} invalid = set(classifications) - valid_symbols if invalid: msg = f"classifications contains keys that are not objective symbols: {invalid}." raise ScalarizationError(msg) active_symbols = set(classifications) active_objectives = [obj for obj in problem.objectives if obj.symbol in active_symbols] need_current = {sym for sym, (cls, _) in classifications.items() if cls in ("<", "<=", "=")} missing_current = need_current - set(current_objective_vector) if missing_current: msg = f"current_objective_vector is missing entries for objectives: {missing_current}." raise ScalarizationError(msg) _validate_aug_params(active_symbols, reference_point_aug, weights_aug) ideal_point, nadir_point = _resolve_ideal_nadir(problem, ideal, nadir) corrected_rp_aug = ( { obj.symbol: reference_point_aug[obj.symbol] * -1 if obj.maximize else reference_point_aug[obj.symbol] for obj in active_objectives } if reference_point_aug is not None else None ) alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) default_aug_weights = { obj.symbol: nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta) for obj in active_objectives } aug_expr = _build_aug_expr( weights_aug, active_objectives, default_aug_weights, list(problem.objectives), corrected_rp_aug ) scalarization = ScalarizationFunction( name="Cumulonimbus scalarization objective function", symbol=symbol, func=f"_alpha + {rho}*({aug_expr})", is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) constraints = [] for obj in active_objectives: cls, level = classifications[obj.symbol] range_ = f"{nadir_point[obj.symbol]} - {ideal_point[obj.symbol] - delta}" maximize_flip = " * -1" if obj.maximize else "" current_val = current_objective_vector.get(obj.symbol, 0.0) constraints.extend( _classification_constraints( obj, cls, level, range_, current_val, maximize_flip, ideal_point[obj.symbol], problem ) ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ## Group scalarization Group scalarization functions split from scalarization.py. This module contains all functions with 'group' in their name, previously located in scalarization.py. ### add_group_asf ``` add_group_asf( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Add the achievement scalarizing function for multiple decision makers. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\max\_{i,d} \[w\_{id}(f\_{id}(\\mathbf{x})-\\overline{z}_{id})\] + \\rho \\sum^k_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} &&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - z^{uto}_{id}}). Parameters: | Name | Type | Description | Default | | ------------------ | ------------------------ | --------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to which the scalarization function should be added. | *required* | | `symbol` | `str` | the symbol to reference the added scalarization function. | *required* | | `reference_points` | `list[dict[str, float]]` | a list of reference points as objective dicts. | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | `None` | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | a small scalar used to define the utopian point. Defaults to 1e-6. | `1e-06` | | `rho` | `float` | the weight factor used in the augmentation term. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_asf( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-6, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Add the achievement scalarizing function for multiple decision makers. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\max_{i,d} [w_{id}(f_{id}(\mathbf{x})-\overline{z}_{id})] + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} &&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - z^{uto}_{id}}$. Args: problem (Problem): the problem to which the scalarization function should be added. symbol (str): the symbol to reference the added scalarization function. reference_points (list[dict[str, float]]): a list of reference points as objective dicts. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): a small scalar used to define the utopian point. Defaults to 1e-6. rho (float, optional): the weight factor used in the augmentation term. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ # check reference points for reference_point in reference_points: if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing a value for one or more objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta)) for obj in problem.objectives } # form the max and augmentation terms max_terms = [] aug_exprs = [] for i in range(len(reference_points)): corrected_rp = flip_maximized_objective_values(problem, reference_points[i]) for obj in problem.objectives: max_terms.append(f"({weights[obj.symbol]}) * ({obj.symbol}_min - {corrected_rp[obj.symbol]})") aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) max_terms = ", ".join(max_terms) aug_exprs = " + ".join(aug_exprs) func = f"{Op.MAX}({max_terms}) + {rho} * ({aug_exprs})" scalarization_function = ScalarizationFunction( name="Achievement scalarizing function for multiple decision makers", symbol=symbol, func=func, is_convex=problem.is_convex, is_linear=problem.is_linear, is_twice_differentiable=False, ) problem = problem.add_scalarization(scalarization_function) # get corrected bounds if exist if agg_bounds is not None: bounds = flip_maximized_objective_values(problem, agg_bounds) constraints = [] for obj in problem.objectives: expr = f"({obj.symbol}_min - {bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) problem = problem.add_constraints(constraints) return problem, symbol ``` ### add_group_asf_agg ``` add_group_asf_agg( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Add the achievement scalarizing function for multiple decision makers. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\max\_{i,d} \[w\_{id}(f\_{id}(\\mathbf{x})-\\overline{z}_{id})\] + \\rho \\sum^k_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} &&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - z^{uto}_{id}}). Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | --------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to which the scalarization function should be added. | *required* | | `symbol` | `str` | the symbol to reference the added scalarization function. | *required* | | `agg_aspirations` | `dict[str, float]` | a dictionary of aggregated aspiration levels (min aspirations). | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of aggregated bounds (max bounds). | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | a small scalar used to define the utopian point. Defaults to 1e-6. | `1e-06` | | `rho` | `float` | the weight factor used in the augmentation term. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_asf_agg( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 1e-6, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Add the achievement scalarizing function for multiple decision makers. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\max_{i,d} [w_{id}(f_{id}(\mathbf{x})-\overline{z}_{id})] + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} &&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - z^{uto}_{id}}$. Args: problem (Problem): the problem to which the scalarization function should be added. symbol (str): the symbol to reference the added scalarization function. agg_aspirations (dict[str, float]): a dictionary of aggregated aspiration levels (min aspirations). agg_bounds (dict[str, float]): a dictionary of aggregated bounds (max bounds). ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): a small scalar used to define the utopian point. Defaults to 1e-6. rho (float, optional): the weight factor used in the augmentation term. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) # Correct the aspirations and hard_constraints agg_aspirations = flip_maximized_objective_values(problem, agg_aspirations) agg_bounds = flip_maximized_objective_values(problem, agg_bounds) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta)) for obj in problem.objectives } # form the max and augmentation terms max_terms = [] aug_exprs = [] for obj in problem.objectives: max_terms.append(f"({weights[obj.symbol]}) * ({obj.symbol}_min - {agg_aspirations[obj.symbol]})") aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) max_terms = ", ".join(max_terms) aug_exprs = " + ".join(aug_exprs) func = f"{Op.MAX}({max_terms}) + {rho} * ({aug_exprs})" scalarization_function = ScalarizationFunction( name="Achievement scalarizing function for multiple decision makers", symbol=symbol, func=func, is_convex=problem.is_convex, is_linear=problem.is_linear, is_twice_differentiable=False, ) constraints = [] for obj in problem.objectives: expr = f"({obj.symbol}_min - {agg_bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) problem = problem.add_constraints(constraints) problem = problem.add_scalarization(scalarization_function) return problem, symbol ``` ### add_group_asf_agg_diff ``` add_group_asf_agg_diff( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1000000.0, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Add the differentiable variant of the achievement scalarizing function for multiple decision makers. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\alpha + \\rho \\sum^k\_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} && w\_{id}(f\_{id}(\\mathbf{x})-\\overline{z}\_{id}) - \\alpha \\leq 0,\\ &&&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - z^{uto}_{id}}). Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | --------------------------------------------------------------------------------------------- | ----------- | | `problem` | `Problem` | the problem to which the scalarization function should be added. | *required* | | `symbol` | `str` | the symbol to reference the added scalarization function. | *required* | | `agg_aspirations` | `dict[str, float]` | a dictionary of aggregated aspiration levels (min aspirations). | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | `None` | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | a small scalar used to define the utopian point. Defaults to 1e-6. | `1000000.0` | | `rho` | `float` | the weight factor used in the augmentation term. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_asf_agg_diff( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e6, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Add the differentiable variant of the achievement scalarizing function for multiple decision makers. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\alpha + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} && w_{id}(f_{id}(\mathbf{x})-\overline{z}_{id}) - \alpha \leq 0,\\ &&&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - z^{uto}_{id}}$. Args: problem (Problem): the problem to which the scalarization function should be added. symbol (str): the symbol to reference the added scalarization function. agg_aspirations (dict[str, float]): a dictionary of aggregated aspiration levels (min aspirations). agg_bounds (dict[str, float]): a dictionary of bounds not to violate. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): a small scalar used to define the utopian point. Defaults to 1e-6. rho (float, optional): the weight factor used in the augmentation term. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # Correct the aspirations and hard_constraints agg_aspirations = flip_maximized_objective_values(problem, agg_aspirations) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta)) for obj in problem.objectives } # form the constaint and augmentation expressions # constraint expressions are formed into a list of lists con_terms = [] for obj in problem.objectives: con_terms.append(f"(({weights[obj.symbol]}) * ({obj.symbol}_min - {agg_aspirations[obj.symbol]})) - _alpha") aug_exprs = [] aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) func = f"_alpha + {rho} * ({aug_exprs})" scalarization_function = ScalarizationFunction( name="Differentiable achievement scalarizing function for multiple decision makers", symbol=symbol, func=func, is_convex=problem.is_convex, is_linear=problem.is_linear, is_twice_differentiable=problem.is_twice_differentiable, ) constraints = [] # loop to create a constraint for every objective of every reference point given for obj in problem.objectives: if type(delta) is dict: expr = ( f"({obj.symbol}_min - {agg_aspirations[obj.symbol]}) / " f"({nadir_point[obj.symbol]} - {ideal_point[obj.symbol] - delta[obj.symbol]}) - _alpha" ) else: expr = ( f"({obj.symbol}_min - {agg_aspirations[obj.symbol]}) / " f"({nadir_point[obj.symbol]} - {ideal_point[obj.symbol] - delta}) - _alpha" ) constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_maxcon", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) # get corrected bounds if exist if agg_bounds is not None: bounds = flip_maximized_objective_values(problem, agg_bounds) for obj in problem.objectives: expr = f"({obj.symbol}_min - {bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization_function) return _problem.add_constraints(constraints), symbol ``` ### add_group_asf_diff ``` add_group_asf_diff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1000000.0, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Add the differentiable variant of the achievement scalarizing function for multiple decision makers. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\alpha + \\rho \\sum^k\_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} && w\_{id}(f\_{id}(\\mathbf{x})-\\overline{z}\_{id}) - \\alpha \\leq 0,\\ &&&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - z^{uto}_{id}}). Parameters: | Name | Type | Description | Default | | ------------------ | ------------------------ | --------------------------------------------------------------------------------------------- | ----------- | | `problem` | `Problem` | the problem to which the scalarization function should be added. | *required* | | `symbol` | `str` | the symbol to reference the added scalarization function. | *required* | | `reference_points` | `list[dict[str, float]]` | a list of reference points as objective dicts. | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | `None` | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | a small scalar used to define the utopian point. Defaults to 1e-6. | `1000000.0` | | `rho` | `float` | the weight factor used in the augmentation term. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_asf_diff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e6, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Add the differentiable variant of the achievement scalarizing function for multiple decision makers. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\alpha + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} && w_{id}(f_{id}(\mathbf{x})-\overline{z}_{id}) - \alpha \leq 0,\\ &&&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - z^{uto}_{id}}$. Args: problem (Problem): the problem to which the scalarization function should be added. symbol (str): the symbol to reference the added scalarization function. reference_points (list[dict[str, float]]): a list of reference points as objective dicts. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): a small scalar used to define the utopian point. Defaults to 1e-6. rho (float, optional): the weight factor used in the augmentation term. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ # check reference points for reference_point in reference_points: if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing a value for one or more objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta)) for obj in problem.objectives } # form the constaint and augmentation expressions # constraint expressions are formed into a list of lists con_terms = [] aug_exprs = [] for i in range(len(reference_points)): corrected_rp = flip_maximized_objective_values(problem, reference_points[i]) rp = {} for obj in problem.objectives: rp[obj.symbol] = f"(({weights[obj.symbol]}) * ({obj.symbol}_min - {corrected_rp[obj.symbol]})) - _alpha" con_terms.append(rp) aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) func = f"_alpha + {rho} * ({aug_exprs})" scalarization_function = ScalarizationFunction( name="Differentiable achievement scalarizing function for multiple decision makers", symbol=symbol, func=func, is_convex=problem.is_convex, is_linear=problem.is_linear, is_twice_differentiable=problem.is_twice_differentiable, ) constraints = [] # loop to create a constraint for every objective of every reference point given for i in range(len(reference_points)): for obj in problem.objectives: # since we are subtracting a constant value, the linearity, convexity, # and differentiability of the objective function, and hence the # constraint, should not change. constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_con_{i + 1}", func=con_terms[i][obj.symbol], cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) # get corrected bounds if exist if agg_bounds is not None: bounds = flip_maximized_objective_values(problem, agg_bounds) for obj in problem.objectives: expr = f"({obj.symbol}_min - {bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization_function) return _problem.add_constraints(constraints), symbol ``` ### add_group_guess ``` add_group_guess( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-06, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the non-differentiable variant of the multiple decision maker variant of the GUESS scalarizing function. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\max\_{i,d} \[w\_{id}(f\_{id}(\\mathbf{x})-z^{nad}_{id})\] + \\rho \\sum^k_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} &&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - \\overline{z}_{id}}). Parameters: | Name | Type | Description | Default | | ------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_points` | `list[dict[str, float]]` | a list of dicts with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar to define the utopian point. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_guess( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-6, nadir: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the non-differentiable variant of the multiple decision maker variant of the GUESS scalarizing function. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\max_{i,d} [w_{id}(f_{id}(\mathbf{x})-z^{nad}_{id})] + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} &&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - \overline{z}_{id}}$. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_points (list[dict[str, float]]): a list of dicts with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar to define the utopian point. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check reference points for reference_point in reference_points: if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing value for one or more objectives." raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) # calculate the weights weights = [] for reference_point in reference_points: corrected_rp = flip_maximized_objective_values(problem, reference_point) if type(delta) is dict: weights.append( { obj.symbol: 1 / ((nadir_point[obj.symbol] + delta[obj.symbol]) - (corrected_rp[obj.symbol])) for obj in problem.objectives } ) else: weights.append( { obj.symbol: 1 / ((nadir_point[obj.symbol] + delta) - (corrected_rp[obj.symbol])) for obj in problem.objectives } ) # form the max term max_terms = [] for i in range(len(reference_points)): corrected_rp = flip_maximized_objective_values(problem, reference_points[i]) for obj in problem.objectives: if type(delta) is dict: max_terms.append( f"{weights[i][obj.symbol]} * ({obj.symbol}_min - {nadir_point[obj.symbol] + delta[obj.symbol]} )" ) else: max_terms.append(f"{weights[i][obj.symbol]} * ({obj.symbol}_min - {nadir_point[obj.symbol] + delta})") max_terms = ", ".join(max_terms) # form the augmentation term aug_exprs = [] for i in range(len(reference_points)): aug_expr = " + ".join([f"({weights[i][obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) func = f"{Op.MAX}({max_terms}) + {rho}*({aug_exprs})" scalarization_function = ScalarizationFunction( name="GUESS scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=False, ) problem = problem.add_scalarization(scalarization_function) # get corrected bounds if exist if agg_bounds is not None: bounds = flip_maximized_objective_values(problem, agg_bounds) constraints = [] for obj in problem.objectives: expr = f"({obj.symbol}_min - {bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) problem = problem.add_constraints(constraints) return problem, symbol ``` ### add_group_guess_agg ``` add_group_guess_agg( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the multiple decision maker variant of the GUESS scalarizing function. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\max\_{i,d} \[w\_{id}(f\_{id}(\\mathbf{x})-z^{uto}_{id})\] + \\rho \\sum^k_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} &&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{\\overline{z}_{id} - z^{uto}_{id}}). Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `agg_aspirations` | `dict[str, float]` | a dictionary of aggregated aspiration levels, i.e., min aspirations. | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar value to define the utopian point. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_guess_agg( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 1e-6, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the multiple decision maker variant of the GUESS scalarizing function. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\max_{i,d} [w_{id}(f_{id}(\mathbf{x})-z^{uto}_{id})] + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} &&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{\overline{z}_{id} - z^{uto}_{id}}$. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. agg_aspirations (dict[str, float]): a dictionary of aggregated aspiration levels, i.e., min aspirations. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar value to define the utopian point. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) # Correct the aspirations and hard_constraints agg_aspirations = flip_maximized_objective_values(problem, agg_aspirations) agg_bounds = flip_maximized_objective_values(problem, agg_bounds) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / ((nadir_point[obj.symbol] + delta[obj.symbol]) - (agg_aspirations[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / ((nadir_point[obj.symbol] + delta) - (agg_aspirations[obj.symbol])) for obj in problem.objectives } # form the max and augmentation terms max_terms = [] aug_exprs = [] for obj in problem.objectives: if type(delta) is dict: max_terms.append( f"{weights[obj.symbol]} * ({obj.symbol}_min - {nadir_point[obj.symbol] + delta[obj.symbol]} )" ) else: max_terms.append(f"{weights[obj.symbol]} * ({obj.symbol}_min - {nadir_point[obj.symbol] + delta})") aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) max_terms = ", ".join(max_terms) aug_exprs = " + ".join(aug_exprs) func = f"{Op.MAX}({max_terms}) + {rho} * ({aug_exprs})" scalarization_function = ScalarizationFunction( name="GUESS scalarizing function for multiple decision makers", symbol=symbol, func=func, is_convex=problem.is_convex, is_linear=problem.is_linear, is_twice_differentiable=False, ) constraints = [] for obj in problem.objectives: expr = f"({obj.symbol}_min - {agg_bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) problem = problem.add_constraints(constraints) problem = problem.add_scalarization(scalarization_function) return problem, symbol ``` ### add_group_guess_agg_diff ``` add_group_guess_agg_diff( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-06, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the differentiable variant of the multiple decision maker variant of the GUESS scalarizing function. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\alpha + \\rho \\sum^k\_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} && w\_{id}(f\_{id}(\\mathbf{x})-z^{nad}\_{id}) - \\alpha \\leq 0,\\ &&&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - \\overline{z}_{id}}). Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `agg_aspirations` | `dict[str, float]` | a dictionary of aggregated aspiration levels, i.e., min aspirations. | *required* | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar to define the utopian point. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_guess_agg_diff( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-6, nadir: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the differentiable variant of the multiple decision maker variant of the GUESS scalarizing function. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\alpha + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} && w_{id}(f_{id}(\mathbf{x})-z^{nad}_{id}) - \alpha \leq 0,\\ &&&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - \overline{z}_{id}}$. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. agg_aspirations (dict[str, float]): a dictionary of aggregated aspiration levels, i.e., min aspirations. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar to define the utopian point. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # Correct the aspirations and hard_constraints agg_aspirations = flip_maximized_objective_values(problem, agg_aspirations) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / ((nadir_point[obj.symbol] + delta[obj.symbol]) - (agg_aspirations[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / ((nadir_point[obj.symbol] + delta) - (agg_aspirations[obj.symbol])) for obj in problem.objectives } # form the max term con_terms = [] for obj in problem.objectives: if type(delta) is dict: con_terms.append( f"{weights[obj.symbol]} * ({obj.symbol}_min - {nadir_point[obj.symbol] + delta[obj.symbol]}) - _alpha" ) else: con_terms.append(f"{weights[obj.symbol]} * ({obj.symbol}_min - {nadir_point[obj.symbol] + delta}) - _alpha") # form the augmentation term aug_exprs = [] aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) constraints = [] # loop to create a constraint for every objective of every reference point given for obj in problem.objectives: expr = ( f"({obj.symbol}_min - {nadir_point[obj.symbol]}) / " f"({nadir_point[obj.symbol]} - {agg_aspirations[obj.symbol]}) - _alpha" ) constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_maxcon", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) # get corrected bounds if exist if agg_bounds is not None: bounds = flip_maximized_objective_values(problem, agg_bounds) for obj in problem.objectives: expr = f"({obj.symbol}_min - {bounds[obj.symbol]} - _alpha)" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) func = f"_alpha + {rho}*({aug_exprs})" scalarization = ScalarizationFunction( name="Differentiable GUESS scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_group_guess_diff ``` add_group_guess_diff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-06, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the differentiable variant of the multiple decision maker variant of the GUESS scalarizing function. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\alpha + \\rho \\sum^k\_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} && w\_{id}(f\_{id}(\\mathbf{x})-z^{nad}\_{id}) - \\alpha \\leq 0,\\ &&&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - \\overline{z}_{id}}). Parameters: | Name | Type | Description | Default | | ------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_points` | `list[dict[str, float]]` | a list of dicts with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar to define the utopian point. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_guess_diff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-6, nadir: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the differentiable variant of the multiple decision maker variant of the GUESS scalarizing function. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\alpha + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} && w_{id}(f_{id}(\mathbf{x})-z^{nad}_{id}) - \alpha \leq 0,\\ &&&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - \overline{z}_{id}}$. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_points (list[dict[str, float]]): a list of dicts with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar to define the utopian point. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check reference points for reference_point in reference_points: if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing value for one or more objectives." raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # calculate the weights weights = [] for reference_point in reference_points: corrected_rp = flip_maximized_objective_values(problem, reference_point) if type(delta) is dict: weights.append( { obj.symbol: 1 / ((nadir_point[obj.symbol] + delta[obj.symbol]) - (corrected_rp[obj.symbol])) for obj in problem.objectives } ) else: weights.append( { obj.symbol: 1 / ((nadir_point[obj.symbol] + delta) - (corrected_rp[obj.symbol])) for obj in problem.objectives } ) # form the max term con_terms = [] for i in range(len(reference_points)): corrected_rp = flip_maximized_objective_values(problem, reference_points[i]) rp = {} for obj in problem.objectives: if type(delta) is dict: rp[obj.symbol] = ( f"{weights[i][obj.symbol]} * ({obj.symbol}_min - {nadir_point[obj.symbol] + delta[obj.symbol]})" " - _alpha" ) else: rp[obj.symbol] = ( f"{weights[i][obj.symbol]} * ({obj.symbol}_min - {nadir_point[obj.symbol] + delta}) - _alpha" ) con_terms.append(rp) # form the augmentation term aug_exprs = [] for i in range(len(reference_points)): aug_expr = " + ".join([f"({weights[i][obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) constraints = [] # loop to create a constraint for every objective of every reference point given for i in range(len(reference_points)): for obj in problem.objectives: # since we are subtracting a constant value, the linearity, convexity, # and differentiability of the objective function, and hence the # constraint, should not change. constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_con_{i + 1}", func=con_terms[i][obj.symbol], cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) # get corrected bounds if exist if agg_bounds is not None: bounds = flip_maximized_objective_values(problem, agg_bounds) for obj in problem.objectives: expr = f"({obj.symbol}_min - {bounds[obj.symbol]} - _alpha)" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) func = f"_alpha + {rho}*({aug_exprs})" scalarization = ScalarizationFunction( name="Differentiable GUESS scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_group_nimbus ``` add_group_nimbus( problem: Problem, symbol: str, classifications_list: list[ dict[str, tuple[str, float | None]] ], current_objective_vector: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Implements the multiple decision maker variant of the NIMBUS scalarization function. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\max\_{i\\in I^\<,j\\in I^\\leq,d} \[w\_{id}(f\_{id}(\\mathbf{x})-z^{ideal}_{id}), w_{jd}(f\_{jd}(\\mathbf{x})-\\hat{z}_{jd})\] + \\rho \\sum^k_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} &&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - z^{uto}_{id}}), and (w\_{jd} = \\frac{1}{z^{nad}_{jd} - z^{uto}_{jd}}). The (I)-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - (I^{\<}): values that should improve, - (I^{\\leq}): values that should improve until a given aspiration level (\\hat{z}\_i), - (I^{=}): values that are fine as they are, - (I^{\\geq}): values that can be impaired until some reservation level (\\varepsilon_i), and - (I^{\\diamond}): values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ``` classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. Parameters: | Name | Type | Description | Default | | -------------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to be scalarized. | *required* | | `symbol` | `str` | the symbol given to the scalarization function, i.e., target of the optimization. | *required* | | `classifications_list` | \`list\[dict\[str, tuple\[str, float | None\]\]\]\` | a list of dicts, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or None, depending on the classification. See above for an explanation. | | `current_objective_vector` | `dict[str, float]` | the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | a small scalar used to define the utopian point. Defaults to 0.000001. | `1e-06` | | `rho` | `float` | a small scalar used in the augmentation term. Defaults to 0.000001. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ScalarizationError` | any of the given classifications do not define a classification for all the objective functions or any of the given classifications do not allow at least one objective function value to improve and one to worsen. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ```` def add_group_nimbus( # noqa: C901 problem: Problem, symbol: str, classifications_list: list[dict[str, tuple[str, float | None]]], current_objective_vector: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 0.000001, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 0.000001, ) -> tuple[Problem, str]: r"""Implements the multiple decision maker variant of the NIMBUS scalarization function. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\max_{i\in I^<,j\in I^\leq,d} [w_{id}(f_{id}(\mathbf{x})-z^{ideal}_{id}), w_{jd}(f_{jd}(\mathbf{x})-\hat{z}_{jd})] + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} &&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - z^{uto}_{id}}$, and $w_{jd} = \frac{1}{z^{nad}_{jd} - z^{uto}_{jd}}$. The $I$-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - $I^{<}$: values that should improve, - $I^{\leq}$: values that should improve until a given aspiration level $\hat{z}_i$, - $I^{=}$: values that are fine as they are, - $I^{\geq}$: values that can be impaired until some reservation level $\varepsilon_i$, and - $I^{\diamond}$: values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ```python classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. Args: problem (Problem): the problem to be scalarized. symbol (str): the symbol given to the scalarization function, i.e., target of the optimization. classifications_list (list[dict[str, tuple[str, float | None]]]): a list of dicts, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or `None`, depending on the classification. See above for an explanation. current_objective_vector (dict[str, float]): the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): a small scalar used to define the utopian point. Defaults to 0.000001. rho (float, optional): a small scalar used in the augmentation term. Defaults to 0.000001. Raises: ScalarizationError: any of the given classifications do not define a classification for all the objective functions or any of the given classifications do not allow at least one objective function value to improve and one to worsen. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check that classifications have been provided for all objective functions for classifications in classifications_list: if not objective_dict_has_all_symbols(problem, classifications): msg = ( f"The given classifications {classifications} do not define " "a classification for all the objective functions." ) raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) corrected_current_point = flip_maximized_objective_values(problem, current_objective_vector) bounds = flip_maximized_objective_values(problem, agg_bounds) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta)) for obj in problem.objectives } # max term and constraints max_args = [] constraints = [] for i in range(len(classifications_list)): classifications = classifications_list[i] for obj in problem.objectives: _symbol = obj.symbol match classifications[_symbol]: case ("<", _): max_expr = f"{weights[_symbol]} * ({_symbol}_min - {ideal_point[_symbol]})" max_args.append(max_expr) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("<=", aspiration): # if obj is to be maximized, then the current aspiration value needs to be multiplied by -1 max_expr = ( f"{weights[_symbol]} * ({_symbol}_min - {aspiration * -1 if obj.maximize else aspiration})" ) max_args.append(max_expr) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement until constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_lte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("=", _): # not relevant for this group scalarization pass case ">=": con_expr = f"{_symbol}_min - {bounds[_symbol]} " constraints.append( Constraint( name=f"Worsen until constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_gte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("0", _): # not relevant for this scalarization pass case (c, _): msg = ( f"Warning! The classification {c} was supplied, but it is not supported." "Must be one of ['<', '<=', '0', '=', '>=']" ) max_expr = f"Max({','.join(max_args)})" # form the augmentation term aug_exprs = [] for _ in range(len(classifications_list)): aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) func = f"{max_expr} + {rho} * ({aug_exprs})" scalarization = ScalarizationFunction( name="NIMBUS scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=False, ) _problem = problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ```` ### add_group_nimbus_compromise ``` add_group_nimbus_compromise( problem: Problem, symbol: str, group_classification: dict[ str, tuple[ Literal["improve", "worsen", "conflict"], list[float], ], ], current_objective_vector: dict[str, float], *, delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, find_compromise: bool = True, ) -> tuple[Problem, str] ``` Add a group-based NIMBUS scalarization (multiple decision-maker variant) to a Problem. This function constructs and attaches a NIMBUS-style scalarization objective and corresponding constraints derived from a group-level classification of objectives. It supports three group classification types for each objective: - "improve": the group wants the objective to improve relative to the provided current objective vector; - "worsen": the group accepts a worsening of the objective but enforces an aggregate bound (agg_bounds); - "conflict": the group contains conflicting preferences; when find_compromise is True a compromise target is formed (median) and used like an "improve" preference if the compromise is an improvement, otherwise the original current point is enforced as in the "improve" fallback when find_compromise is False. Behavior summary - Validates that a classification is provided for every objective in the problem. - Ensures an ideal and nadir point are available (uses corrected problem values if not supplied; raises ScalarizationError otherwise). - Converts objective values for maximization problems to the same minimization convention used internally. - Computes normalization weights for each objective using nadir, ideal, and the provided delta (scalar or per-objective dict), i.e. weight_i = 1 / (nadir_i - (ideal_i - delta_i)). - For each objective, depending on the group classification: - "improve": may add a term to the scalarization's max(...) expression if the chosen target represents an improvement; always adds an improvement constraint that enforces the objective to be at least as good as the current point. - "worsen": adds a constraint preventing the objective from exceeding the provided agg_bounds value. - "conflict": if find_compromise is True, selects the median target from the group's values and treats it like an "improve" (if it improves); otherwise enforces the current point via an improvement constraint. - Constructs a scalarization objective of the form: Max(weight_i * (obj_i_min - ideal_i) for selected i) + rho * sum(weight_j * obj_j_min) where obj_k_min denotes the (possibly flipped) objective expression used for minimization in the scalarization and rho is the small augmentation coefficient. - Creates Constraint objects (with names and symbols derived from each objective) and appends them to the problem along with the new ScalarizationFunction. Parameters - problem (Problem): The problem instance to which the scalarization and constraints will be added. The function calls problem.add_scalarization(...) and problem.add_constraints(...). - symbol (str): Symbol/name for the new scalarization (target of optimization). - group_classification (dict\[str, tuple\[str, list[float]\]\]): A mapping from objective symbol -> (classification, group_targets). The classification must be one of: "improve", "worsen", "conflict". The second element is a list of numerical target values provided by the group members for that objective. Interpretation: - For "improve": the most ambitious group target is taken (currently the maximum for maximization problems or minimum for minimization problems). - For "worsen": the strictest bound from the group is used to form a bound constraint (implementation currently uses agg_bounds instead). - For "conflict": the median of the group targets is used when find_compromise is True; otherwise treated like enforcing the current point. - current_objective_vector (dict[str, float]): Objective values corresponding to a (reference) Pareto-optimal solution; used as baseline for improvement constraints. - agg_bounds (dict[str, float]): Aggregate bounds that must not be violated for objectives marked as "worsen" (values are converted appropriately for maximization objectives). - delta (dict[str, float] | float, optional): Small utopian offset used to compute normalization weights. If a dict is given it should map objective symbols to deltas; if a scalar is given the same delta is used for all objectives. Default: 1e-6. - ideal (dict[str, float] | None, optional): Ideal point values. If None, the function attempts to obtain a corrected ideal point from the problem instance. - nadir (dict[str, float] | None, optional): Nadir point values. If None, the function attempts to obtain a corrected nadir point from the problem instance. - rho (float, optional): Small augmentation coefficient multiplied by the linear sum of weighted objectives to break ties and enforce weak Pareto optimality. Default: 1e-6. - find_compromise (bool, optional): If True, conflicting objectives use a median compromise target; otherwise conflicts are enforced to keep current values. Default: True. - tuple\[Problem, str\]: A tuple containing: - A new Problem instance (or the original problem mutated/augmented depending on Problem.add_scalarization/Problem.add_constraints semantics) with the scalarization objective and additional constraints appended. - The symbol (str) of the added scalarization. - ScalarizationError: if - the group_classification mapping does not provide a classification for every objective in the problem, or - neither an explicit ideal nor a computable corrected ideal is available, or - neither an explicit nadir nor a computable corrected nadir is available. - KeyError: if group_classification does not contain entries for objective symbols referenced in the problem (note: this will typically surface as KeyError during processing). Notes and implementation details - The function internally flips maximization objectives into a minimization form using flip_maximized_objective_values(...) so all scalarization math assumes minimization semantics. - Weight computation uses (nadir - (ideal - delta)); ensure delta is chosen so denominator is positive. - The "max" term in the scalarization is constructed from selected improving objectives only; the augmentation term is the (weighted) sum over all objectives. - Constraint objects are created with ConstraintTypeEnum.LTE and names/symbols formatted like "improvement constraint for {symbol}" or "Worsen until constraint for {symbol}". - The function currently prints group_classification (left for debugging) — this side effect may be removed in production code. Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_nimbus_compromise( problem: Problem, symbol: str, group_classification: dict[str, tuple[Literal["improve", "worsen", "conflict"], list[float]]], current_objective_vector: dict[str, float], *, delta: dict[str, float] | float = 0.000001, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 0.000001, find_compromise: bool = True, ) -> tuple[Problem, str]: """Add a group-based NIMBUS scalarization (multiple decision-maker variant) to a Problem. This function constructs and attaches a NIMBUS-style scalarization objective and corresponding constraints derived from a group-level classification of objectives. It supports three group classification types for each objective: - "improve": the group wants the objective to improve relative to the provided current objective vector; - "worsen": the group accepts a worsening of the objective but enforces an aggregate bound (agg_bounds); - "conflict": the group contains conflicting preferences; when find_compromise is True a compromise target is formed (median) and used like an "improve" preference if the compromise is an improvement, otherwise the original current point is enforced as in the "improve" fallback when find_compromise is False. Behavior summary - Validates that a classification is provided for every objective in the problem. - Ensures an ideal and nadir point are available (uses corrected problem values if not supplied; raises ScalarizationError otherwise). - Converts objective values for maximization problems to the same minimization convention used internally. - Computes normalization weights for each objective using nadir, ideal, and the provided delta (scalar or per-objective dict), i.e. weight_i = 1 / (nadir_i - (ideal_i - delta_i)). - For each objective, depending on the group classification: - "improve": may add a term to the scalarization's max(...) expression if the chosen target represents an improvement; always adds an improvement constraint that enforces the objective to be at least as good as the current point. - "worsen": adds a constraint preventing the objective from exceeding the provided agg_bounds value. - "conflict": if find_compromise is True, selects the median target from the group's values and treats it like an "improve" (if it improves); otherwise enforces the current point via an improvement constraint. - Constructs a scalarization objective of the form: Max(weight_i * (obj_i_min - ideal_i) for selected i) + rho * sum(weight_j * obj_j_min) where obj_k_min denotes the (possibly flipped) objective expression used for minimization in the scalarization and rho is the small augmentation coefficient. - Creates Constraint objects (with names and symbols derived from each objective) and appends them to the problem along with the new ScalarizationFunction. Parameters - problem (Problem): The problem instance to which the scalarization and constraints will be added. The function calls problem.add_scalarization(...) and problem.add_constraints(...). - symbol (str): Symbol/name for the new scalarization (target of optimization). - group_classification (dict[str, tuple[str, list[float]]]): A mapping from objective symbol -> (classification, group_targets). The classification must be one of: "improve", "worsen", "conflict". The second element is a list of numerical target values provided by the group members for that objective. Interpretation: - For "improve": the most ambitious group target is taken (currently the maximum for maximization problems or minimum for minimization problems). - For "worsen": the strictest bound from the group is used to form a bound constraint (implementation currently uses agg_bounds instead). - For "conflict": the median of the group targets is used when find_compromise is True; otherwise treated like enforcing the current point. - current_objective_vector (dict[str, float]): Objective values corresponding to a (reference) Pareto-optimal solution; used as baseline for improvement constraints. - agg_bounds (dict[str, float]): Aggregate bounds that must not be violated for objectives marked as "worsen" (values are converted appropriately for maximization objectives). - delta (dict[str, float] | float, optional): Small utopian offset used to compute normalization weights. If a dict is given it should map objective symbols to deltas; if a scalar is given the same delta is used for all objectives. Default: 1e-6. - ideal (dict[str, float] | None, optional): Ideal point values. If None, the function attempts to obtain a corrected ideal point from the problem instance. - nadir (dict[str, float] | None, optional): Nadir point values. If None, the function attempts to obtain a corrected nadir point from the problem instance. - rho (float, optional): Small augmentation coefficient multiplied by the linear sum of weighted objectives to break ties and enforce weak Pareto optimality. Default: 1e-6. - find_compromise (bool, optional): If True, conflicting objectives use a median compromise target; otherwise conflicts are enforced to keep current values. Default: True. Returns: - tuple[Problem, str]: A tuple containing: - A new Problem instance (or the original problem mutated/augmented depending on Problem.add_scalarization/Problem.add_constraints semantics) with the scalarization objective and additional constraints appended. - The symbol (str) of the added scalarization. Raises: - ScalarizationError: if - the group_classification mapping does not provide a classification for every objective in the problem, or - neither an explicit ideal nor a computable corrected ideal is available, or - neither an explicit nadir nor a computable corrected nadir is available. - KeyError: if group_classification does not contain entries for objective symbols referenced in the problem (note: this will typically surface as KeyError during processing). Notes and implementation details - The function internally flips maximization objectives into a minimization form using flip_maximized_objective_values(...) so all scalarization math assumes minimization semantics. - Weight computation uses (nadir - (ideal - delta)); ensure delta is chosen so denominator is positive. - The "max" term in the scalarization is constructed from selected improving objectives only; the augmentation term is the (weighted) sum over all objectives. - Constraint objects are created with ConstraintTypeEnum.LTE and names/symbols formatted like "improvement constraint for {symbol}" or "Worsen until constraint for {symbol}". - The function currently prints group_classification (left for debugging) — this side effect may be removed in production code. """ # check that classifications have been provided for all objective functions if not objective_dict_has_all_symbols(problem, group_classification): msg = ( f"The given classifications {group_classification} do not define " "a classification for all the objective functions." ) raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) corrected_current_point = flip_maximized_objective_values(problem, current_objective_vector) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta)) for obj in problem.objectives } # max term and constraints max_args = [] constraints = [] # Derive the group classifications for obj in problem.objectives: _symbol = obj.symbol match group_classification[_symbol][0]: case "improve": # Take the most ambitious target among the group (could be changed to something else as well) target = ( -max(group_classification[_symbol][1]) if obj.maximize else min(group_classification[_symbol][1]) ) if target < corrected_current_point[_symbol]: max_expr = f"{weights[_symbol]} * ({_symbol}_min - {target})" max_args.append(max_expr) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case "worsen": # Take the strictest constraint given by the group (could be changed to something else as well) target = ( -max(group_classification[_symbol][1]) if obj.maximize else min(group_classification[_symbol][1]) ) con_expr = f"{_symbol}_min - {target} " constraints.append( Constraint( name=f"Worsen until constraint for {_symbol}", symbol=f"{_symbol}_gte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case "conflict": if find_compromise: # Take the median target from the group (could be changed to something else as well) target = np.median(group_classification[_symbol][1]) max_expr = f"{weights[_symbol]} * ({_symbol}_min - {target})" max_args.append(max_expr) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]} - { (nadir_point[_symbol] - ideal_point[_symbol]) / 20 }" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) else: con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case _: msg = ( f"Warning! The classification {group_classification[_symbol]} was " "supplied, but it is not supported. " "Must be one of ['improve', 'worsen', 'conflict']" ) max_expr = f"Max({','.join(max_args)})" # form the augmentation term aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) func = f"{max_expr} + {rho} * ({aug_expr})" scalarization = ScalarizationFunction( name="NIMBUS scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=False, ) _problem = problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_group_nimbus_compromise_diff ``` add_group_nimbus_compromise_diff( problem: Problem, symbol: str, group_classification: dict[ str, tuple[ Literal["improve", "worsen", "conflict"], list[float], ], ], current_objective_vector: dict[str, float], *, delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, find_compromise: bool = True, ) -> tuple[Problem, str] ``` Add a group-based NIMBUS scalarization (multiple decision-maker variant) to a Problem. This function constructs and attaches a NIMBUS-style scalarization objective and corresponding constraints derived from a group-level classification of objectives. It supports three group classification types for each objective: - "improve": the group wants the objective to improve relative to the provided current objective vector; - "worsen": the group accepts a worsening of the objective but enforces an aggregate bound (agg_bounds); - "conflict": the group contains conflicting preferences; when find_compromise is True a compromise target is formed (median) and used like an "improve" preference if the compromise is an improvement, otherwise the original current point is enforced as in the "improve" fallback when find_compromise is False. Behavior summary - Validates that a classification is provided for every objective in the problem. - Ensures an ideal and nadir point are available (uses corrected problem values if not supplied; raises ScalarizationError otherwise). - Converts objective values for maximization problems to the same minimization convention used internally. - Computes normalization weights for each objective using nadir, ideal, and the provided delta (scalar or per-objective dict), i.e. weight_i = 1 / (nadir_i - (ideal_i - delta_i)). - For each objective, depending on the group classification: - "improve": may add a term to the scalarization's max(...) expression if the chosen target represents an improvement; always adds an improvement constraint that enforces the objective to be at least as good as the current point. - "worsen": adds a constraint preventing the objective from exceeding the provided agg_bounds value. - "conflict": if find_compromise is True, selects the median target from the group's values and treats it like an "improve" (if it improves); otherwise enforces the current point via an improvement constraint. - Constructs a scalarization objective of the form: Max(weight_i * (obj_i_min - ideal_i) for selected i) + rho * sum(weight_j * obj_j_min) where obj_k_min denotes the (possibly flipped) objective expression used for minimization in the scalarization and rho is the small augmentation coefficient. - Creates Constraint objects (with names and symbols derived from each objective) and appends them to the problem along with the new ScalarizationFunction. Parameters - problem (Problem): The problem instance to which the scalarization and constraints will be added. The function calls problem.add_scalarization(...) and problem.add_constraints(...). - symbol (str): Symbol/name for the new scalarization (target of optimization). - group_classification (dict\[str, tuple\[str, list[float]\]\]): A mapping from objective symbol -> (classification, group_targets). The classification must be one of: "improve", "worsen", "conflict". The second element is a list of numerical target values provided by the group members for that objective. Interpretation: - For "improve": the most ambitious group target is taken (currently the maximum for maximization problems or minimum for minimization problems). - For "worsen": the strictest bound from the group is used to form a bound constraint (implementation currently uses agg_bounds instead). - For "conflict": the median of the group targets is used when find_compromise is True; otherwise treated like enforcing the current point. - current_objective_vector (dict[str, float]): Objective values corresponding to a (reference) Pareto-optimal solution; used as baseline for improvement constraints. - agg_bounds (dict[str, float]): Aggregate bounds that must not be violated for objectives marked as "worsen" (values are converted appropriately for maximization objectives). - delta (dict[str, float] | float, optional): Small utopian offset used to compute normalization weights. If a dict is given it should map objective symbols to deltas; if a scalar is given the same delta is used for all objectives. Default: 1e-6. - ideal (dict[str, float] | None, optional): Ideal point values. If None, the function attempts to obtain a corrected ideal point from the problem instance. - nadir (dict[str, float] | None, optional): Nadir point values. If None, the function attempts to obtain a corrected nadir point from the problem instance. - rho (float, optional): Small augmentation coefficient multiplied by the linear sum of weighted objectives to break ties and enforce weak Pareto optimality. Default: 1e-6. - find_compromise (bool, optional): If True, conflicting objectives use a median compromise target; otherwise conflicts are enforced to keep current values. Default: True. - tuple\[Problem, str\]: A tuple containing: - A new Problem instance (or the original problem mutated/augmented depending on Problem.add_scalarization/Problem.add_constraints semantics) with the scalarization objective and additional constraints appended. - The symbol (str) of the added scalarization. - ScalarizationError: if - the group_classification mapping does not provide a classification for every objective in the problem, or - neither an explicit ideal nor a computable corrected ideal is available, or - neither an explicit nadir nor a computable corrected nadir is available. - KeyError: if group_classification does not contain entries for objective symbols referenced in the problem (note: this will typically surface as KeyError during processing). Notes and implementation details - The function internally flips maximization objectives into a minimization form using flip_maximized_objective_values(...) so all scalarization math assumes minimization semantics. - Weight computation uses (nadir - (ideal - delta)); ensure delta is chosen so denominator is positive. - The "max" term in the scalarization is constructed from selected improving objectives only; the augmentation term is the (weighted) sum over all objectives. - Constraint objects are created with ConstraintTypeEnum.LTE and names/symbols formatted like "improvement constraint for {symbol}" or "Worsen until constraint for {symbol}". - The function currently prints group_classification (left for debugging) — this side effect may be removed in production code. Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_nimbus_compromise_diff( problem: Problem, symbol: str, group_classification: dict[str, tuple[Literal["improve", "worsen", "conflict"], list[float]]], current_objective_vector: dict[str, float], *, delta: dict[str, float] | float = 0.000001, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 0.000001, find_compromise: bool = True, ) -> tuple[Problem, str]: """Add a group-based NIMBUS scalarization (multiple decision-maker variant) to a Problem. This function constructs and attaches a NIMBUS-style scalarization objective and corresponding constraints derived from a group-level classification of objectives. It supports three group classification types for each objective: - "improve": the group wants the objective to improve relative to the provided current objective vector; - "worsen": the group accepts a worsening of the objective but enforces an aggregate bound (agg_bounds); - "conflict": the group contains conflicting preferences; when find_compromise is True a compromise target is formed (median) and used like an "improve" preference if the compromise is an improvement, otherwise the original current point is enforced as in the "improve" fallback when find_compromise is False. Behavior summary - Validates that a classification is provided for every objective in the problem. - Ensures an ideal and nadir point are available (uses corrected problem values if not supplied; raises ScalarizationError otherwise). - Converts objective values for maximization problems to the same minimization convention used internally. - Computes normalization weights for each objective using nadir, ideal, and the provided delta (scalar or per-objective dict), i.e. weight_i = 1 / (nadir_i - (ideal_i - delta_i)). - For each objective, depending on the group classification: - "improve": may add a term to the scalarization's max(...) expression if the chosen target represents an improvement; always adds an improvement constraint that enforces the objective to be at least as good as the current point. - "worsen": adds a constraint preventing the objective from exceeding the provided agg_bounds value. - "conflict": if find_compromise is True, selects the median target from the group's values and treats it like an "improve" (if it improves); otherwise enforces the current point via an improvement constraint. - Constructs a scalarization objective of the form: Max(weight_i * (obj_i_min - ideal_i) for selected i) + rho * sum(weight_j * obj_j_min) where obj_k_min denotes the (possibly flipped) objective expression used for minimization in the scalarization and rho is the small augmentation coefficient. - Creates Constraint objects (with names and symbols derived from each objective) and appends them to the problem along with the new ScalarizationFunction. Parameters - problem (Problem): The problem instance to which the scalarization and constraints will be added. The function calls problem.add_scalarization(...) and problem.add_constraints(...). - symbol (str): Symbol/name for the new scalarization (target of optimization). - group_classification (dict[str, tuple[str, list[float]]]): A mapping from objective symbol -> (classification, group_targets). The classification must be one of: "improve", "worsen", "conflict". The second element is a list of numerical target values provided by the group members for that objective. Interpretation: - For "improve": the most ambitious group target is taken (currently the maximum for maximization problems or minimum for minimization problems). - For "worsen": the strictest bound from the group is used to form a bound constraint (implementation currently uses agg_bounds instead). - For "conflict": the median of the group targets is used when find_compromise is True; otherwise treated like enforcing the current point. - current_objective_vector (dict[str, float]): Objective values corresponding to a (reference) Pareto-optimal solution; used as baseline for improvement constraints. - agg_bounds (dict[str, float]): Aggregate bounds that must not be violated for objectives marked as "worsen" (values are converted appropriately for maximization objectives). - delta (dict[str, float] | float, optional): Small utopian offset used to compute normalization weights. If a dict is given it should map objective symbols to deltas; if a scalar is given the same delta is used for all objectives. Default: 1e-6. - ideal (dict[str, float] | None, optional): Ideal point values. If None, the function attempts to obtain a corrected ideal point from the problem instance. - nadir (dict[str, float] | None, optional): Nadir point values. If None, the function attempts to obtain a corrected nadir point from the problem instance. - rho (float, optional): Small augmentation coefficient multiplied by the linear sum of weighted objectives to break ties and enforce weak Pareto optimality. Default: 1e-6. - find_compromise (bool, optional): If True, conflicting objectives use a median compromise target; otherwise conflicts are enforced to keep current values. Default: True. Returns: - tuple[Problem, str]: A tuple containing: - A new Problem instance (or the original problem mutated/augmented depending on Problem.add_scalarization/Problem.add_constraints semantics) with the scalarization objective and additional constraints appended. - The symbol (str) of the added scalarization. Raises: - ScalarizationError: if - the group_classification mapping does not provide a classification for every objective in the problem, or - neither an explicit ideal nor a computable corrected ideal is available, or - neither an explicit nadir nor a computable corrected nadir is available. - KeyError: if group_classification does not contain entries for objective symbols referenced in the problem (note: this will typically surface as KeyError during processing). Notes and implementation details - The function internally flips maximization objectives into a minimization form using flip_maximized_objective_values(...) so all scalarization math assumes minimization semantics. - Weight computation uses (nadir - (ideal - delta)); ensure delta is chosen so denominator is positive. - The "max" term in the scalarization is constructed from selected improving objectives only; the augmentation term is the (weighted) sum over all objectives. - Constraint objects are created with ConstraintTypeEnum.LTE and names/symbols formatted like "improvement constraint for {symbol}" or "Worsen until constraint for {symbol}". - The function currently prints group_classification (left for debugging) — this side effect may be removed in production code. """ # check that classifications have been provided for all objective functions if not objective_dict_has_all_symbols(problem, group_classification): msg = ( f"The given classifications {group_classification} do not define " "a classification for all the objective functions." ) raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) corrected_current_point = flip_maximized_objective_values(problem, current_objective_vector) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta)) for obj in problem.objectives } # max term and constraints constraints = [] # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # Derive the group classifications for obj in problem.objectives: _symbol = obj.symbol match group_classification[_symbol][0]: case "improve": # Take the most ambitious target among the group (could be changed to something else as well) target = ( -max(group_classification[_symbol][1]) if obj.maximize else min(group_classification[_symbol][1]) ) if target < corrected_current_point[_symbol]: max_expr = f"{weights[_symbol]} * ({_symbol}_min - {target}) - _alpha" constraints.append( Constraint( name=f"Max term linearization for {_symbol}", symbol=f"max_con_{_symbol}", func=max_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case "worsen": # Take the strictest constraint given by the group (could be changed to something else as well) target = ( -max(group_classification[_symbol][1]) if obj.maximize else min(group_classification[_symbol][1]) ) con_expr = f"{_symbol}_min - {target} " constraints.append( Constraint( name=f"Worsen until constraint for {_symbol}", symbol=f"{_symbol}_gte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case "conflict": if find_compromise: # Take the median target from the group (could be changed to something else as well) target = np.median(group_classification[_symbol][1]) max_expr = f"{weights[_symbol]} * ({_symbol}_min - {target}) - _alpha" constraints.append( Constraint( name=f"Max term linearization for {_symbol}", symbol=f"max_con_{_symbol}", func=max_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]} - { (nadir_point[_symbol] - ideal_point[_symbol]) / 20 }" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) else: con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case _: msg = ( f"Warning! The classification {group_classification[_symbol]} was " "supplied, but it is not supported." "Must be one of ['improve', 'worsen', 'conflict']" ) # form the augmentation term aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) func = f"_alpha + {rho} * ({aug_expr})" scalarization = ScalarizationFunction( name="NIMBUS scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_group_nimbus_diff ``` add_group_nimbus_diff( problem: Problem, symbol: str, classifications_list: list[ dict[str, tuple[str, float | None]] ], current_objective_vector: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Implements the differentiable variant of the multiple decision maker of the group NIMBUS scalarization function. The scalarization function is defined as follows: \[\\begin{align} \\mbox{minimize} \\quad &\\alpha + \\rho \\sum^k\_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x})\\ \\mbox{subject to} \\quad & w\_{id}(f\_{id}(\\mathbf{x})-z^{ideal}_{id}) - \\alpha \\leq 0 \\quad & \\forall i \\in I^\<,\\ & w_{jd}(f\_{jd}(\\mathbf{x})-\\hat{z}\_{jd}) - \\alpha \\leq 0 \\quad & \\forall j \\in I^\\leq ,\\ & f_i(\\mathbf{x}) - f_i(\\mathbf{x_c}) \\leq 0 \\quad & \\forall i \\in I^< \\cup I^\\leq \\cup I^= ,\\ & f_i(\\mathbf{x}) - \\epsilon_i \\leq 0 \\quad & \\forall i \\in I^\\geq ,\\ & \\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - z^{uto}_{id}}), and (w\_{jd} = \\frac{1}{z^{nad}_{jd} - z^{uto}_{jd}}). The (I)-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - (I^{\<}): values that should improve, - (I^{\\leq}): values that should improve until a given aspiration level (\\hat{z}\_i), - (I^{=}): values that are fine as they are, - (I^{\\geq}): values that can be impaired until some reservation level (\\varepsilon_i), and - (I^{\\diamond}): values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ``` classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. Parameters: | Name | Type | Description | Default | | -------------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to be scalarized. | *required* | | `symbol` | `str` | the symbol given to the scalarization function, i.e., target of the optimization. | *required* | | `classifications_list` | \`list\[dict\[str, tuple\[str, float | None\]\]\]\` | a list of dicts, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or None, depending on the classification. See above for an explanation. | | `current_objective_vector` | `dict[str, float]` | the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | a small scalar used to define the utopian point. Defaults to 0.000001. | `1e-06` | | `rho` | `float` | a small scalar used in the augmentation term. Defaults to 0.000001. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ScalarizationError` | any of the given classifications do not define a classification for all the objective functions or any of the given classifications do not allow at least one objective function value to improve and one to worsen. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ```` def add_group_nimbus_diff( # noqa: C901 problem: Problem, symbol: str, classifications_list: list[dict[str, tuple[str, float | None]]], current_objective_vector: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 0.000001, ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 0.000001, ) -> tuple[Problem, str]: r"""Implements the differentiable variant of the multiple decision maker of the group NIMBUS scalarization function. The scalarization function is defined as follows: \begin{align} \mbox{minimize} \quad &\alpha + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x})\\ \mbox{subject to} \quad & w_{id}(f_{id}(\mathbf{x})-z^{ideal}_{id}) - \alpha \leq 0 \quad & \forall i \in I^<,\\ & w_{jd}(f_{jd}(\mathbf{x})-\hat{z}_{jd}) - \alpha \leq 0 \quad & \forall j \in I^\leq ,\\ & f_i(\mathbf{x}) - f_i(\mathbf{x_c}) \leq 0 \quad & \forall i \in I^< \cup I^\leq \cup I^= ,\\ & f_i(\mathbf{x}) - \epsilon_i \leq 0 \quad & \forall i \in I^\geq ,\\ & \mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - z^{uto}_{id}}$, and $w_{jd} = \frac{1}{z^{nad}_{jd} - z^{uto}_{jd}}$. The $I$-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - $I^{<}$: values that should improve, - $I^{\leq}$: values that should improve until a given aspiration level $\hat{z}_i$, - $I^{=}$: values that are fine as they are, - $I^{\geq}$: values that can be impaired until some reservation level $\varepsilon_i$, and - $I^{\diamond}$: values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ```python classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. Args: problem (Problem): the problem to be scalarized. symbol (str): the symbol given to the scalarization function, i.e., target of the optimization. classifications_list (list[dict[str, tuple[str, float | None]]]): a list of dicts, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or `None`, depending on the classification. See above for an explanation. current_objective_vector (dict[str, float]): the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): a small scalar used to define the utopian point. Defaults to 0.000001. rho (float, optional): a small scalar used in the augmentation term. Defaults to 0.000001. Raises: ScalarizationError: any of the given classifications do not define a classification for all the objective functions or any of the given classifications do not allow at least one objective function value to improve and one to worsen. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check that classifications have been provided for all objective functions for classifications in classifications_list: if not objective_dict_has_all_symbols(problem, classifications): msg = ( f"The given classifications {classifications} do not define " "a classification for all the objective functions." ) raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) corrected_current_point = flip_maximized_objective_values(problem, current_objective_vector) bounds = flip_maximized_objective_values(problem, agg_bounds) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta[obj.symbol])) for obj in problem.objectives } else: weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta)) for obj in problem.objectives } constraints = [] for i in range(len(classifications_list)): classifications = classifications_list[i] for obj in problem.objectives: _symbol = obj.symbol match classifications[_symbol]: case ("<", _): max_expr = f"{weights[_symbol]} * ({_symbol}_min - {ideal_point[_symbol]}) - _alpha" constraints.append( Constraint( name=f"Max term linearization for {_symbol}", symbol=f"max_con_{_symbol}_{i + 1}", func=max_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]} - _alpha" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("<=", aspiration): # if obj is to be maximized, then the current aspiration value needs to be multiplied by -1 max_expr = ( f"{weights[_symbol]} * ({_symbol}_min - {aspiration * -1 if obj.maximize else aspiration}) " "- _alpha" ) constraints.append( Constraint( name=f"Max term linearization for {_symbol}", symbol=f"max_con_{_symbol}_{i + 1}", func=max_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]} - _alpha" constraints.append( Constraint( name=f"improvement until constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_lte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("=", _): # not relevant for this group scalarization pass case ">=": con_expr = f"{_symbol}_min - {bounds[_symbol]}" constraints.append( Constraint( name=f"Worsen until constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_gte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("0", _): # not relevant for this scalarization pass case (c, _): msg = ( f"Warning! The classification {c} was supplied, but it is not supported." "Must be one of ['<', '<=', '0', '=', '>=']" ) # form the augmentation term aug_exprs = [] for _ in range(len(classifications_list)): aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) func = f"_alpha + {rho} * ({aug_exprs})" scalarization_function = ScalarizationFunction( name="Differentiable NIMBUS scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization_function) return _problem.add_constraints(constraints), symbol ```` ### add_group_nimbus_sf ``` add_group_nimbus_sf( problem: Problem, symbol: str, classifications_list: list[ dict[str, tuple[str, float | None]] ], current_objective_vector: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, delta: float = 1e-06, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Implements the multiple decision maker variant of the NIMBUS scalarization function. Variant without aggregated bounds. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\max\_{i\\in I^\<,j\\in I^\\leq,d} \[w\_{id}(f\_{id}(\\mathbf{x})-z^{ideal}_{id}), w_{jd}(f\_{jd}(\\mathbf{x})-\\hat{z}_{jd})\] + \\rho \\sum^k_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} &&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{z^{nad}_{id} - z^{uto}_{id}}), and (w\_{jd} = \\frac{1}{z^{nad}_{jd} - z^{uto}_{jd}}). The (I)-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - (I^{\<}): values that should improve, - (I^{\\leq}): values that should improve until a given aspiration level (\\hat{z}\_i), - (I^{=}): values that are fine as they are, - (I^{\\geq}): values that can be impaired until some reservation level (\\varepsilon_i), and - (I^{\\diamond}): values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ``` classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. Parameters: | Name | Type | Description | Default | | -------------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to be scalarized. | *required* | | `symbol` | `str` | the symbol given to the scalarization function, i.e., target of the optimization. | *required* | | `classifications_list` | \`list\[dict\[str, tuple\[str, float | None\]\]\]\` | a list of dicts, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or None, depending on the classification. See above for an explanation. | | `current_objective_vector` | `dict[str, float]` | the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `nadir` | `dict[str, float]` | nadir point values. If not given, attempt will be made to calculate nadir point from problem. | `None` | | `delta` | `float` | a small scalar used to define the utopian point. Defaults to 0.000001. | `1e-06` | | `rho` | `float` | a small scalar used in the augmentation term. Defaults to 0.000001. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ScalarizationError` | any of the given classifications do not define a classification for all the objective functions or any of the given classifications do not allow at least one objective function value to improve and one to worsen. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ```` def add_group_nimbus_sf( # noqa: C901 problem: Problem, symbol: str, classifications_list: list[dict[str, tuple[str, float | None]]], current_objective_vector: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, delta: float = 0.000001, rho: float = 0.000001, ) -> tuple[Problem, str]: r"""Implements the multiple decision maker variant of the NIMBUS scalarization function. Variant without aggregated bounds. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\max_{i\in I^<,j\in I^\leq,d} [w_{id}(f_{id}(\mathbf{x})-z^{ideal}_{id}), w_{jd}(f_{jd}(\mathbf{x})-\hat{z}_{jd})] + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} &&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{z^{nad}_{id} - z^{uto}_{id}}$, and $w_{jd} = \frac{1}{z^{nad}_{jd} - z^{uto}_{jd}}$. The $I$-sets are related to the classifications given to each objective function value in respect to the current objective vector (e.g., by a decision maker). They are as follows: - $I^{<}$: values that should improve, - $I^{\leq}$: values that should improve until a given aspiration level $\hat{z}_i$, - $I^{=}$: values that are fine as they are, - $I^{\geq}$: values that can be impaired until some reservation level $\varepsilon_i$, and - $I^{\diamond}$: values that are allowed to change freely (not present explicitly in this scalarization function). The aspiration levels and the reservation levels are supplied for each classification, when relevant, in the argument `classifications` as follows: ```python classifications = { "f_1": ("<", None), "f_2": ("<=", 42.1), "f_3": (">=", 22.2), "f_4": ("0", None) } ``` Here, we have assumed four objective functions. The key of the dict is a function's symbol, and the tuple consists of a pair where the left element is the classification (self explanatory, '0' is for objective values that may change freely), the right element is either `None` or an aspiration or a reservation level depending on the classification. Args: problem (Problem): the problem to be scalarized. symbol (str): the symbol given to the scalarization function, i.e., target of the optimization. classifications_list (list[dict[str, tuple[str, float | None]]]): a list of dicts, where the key is a symbol of an objective function, and the value is a tuple with a classification and an aspiration or a reservation level, or `None`, depending on the classification. See above for an explanation. current_objective_vector (dict[str, float]): the current objective vector that corresponds to a Pareto optimal solution. The classifications are assumed to been given in respect to this vector. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. nadir (dict[str, float], optional): nadir point values. If not given, attempt will be made to calculate nadir point from problem. delta (float, optional): a small scalar used to define the utopian point. Defaults to 0.000001. rho (float, optional): a small scalar used in the augmentation term. Defaults to 0.000001. Raises: ScalarizationError: any of the given classifications do not define a classification for all the objective functions or any of the given classifications do not allow at least one objective function value to improve and one to worsen. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check that classifications have been provided for all objective functions for classifications in classifications_list: if not objective_dict_has_all_symbols(problem, classifications): msg = ( f"The given classifications {classifications} do not define " "a classification for all the objective functions." ) raise ScalarizationError(msg) # check that at least one objective function is allowed to be improved and one is # allowed to worsen if not any(classifications[obj.symbol][0] in ["<", "<="] for obj in problem.objectives) or not any( classifications[obj.symbol][0] in [">=", "0"] for obj in problem.objectives ): msg = ( f"The given classifications {classifications} should allow at least one objective function value " "to improve and one to worsen." ) raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # check if nadir point is specified # if not specified, try to calculate corrected nadir point if nadir is not None: nadir_point = nadir elif problem.get_nadir_point() is not None: nadir_point = get_corrected_nadir(problem) else: msg = "Nadir point not defined!" raise ScalarizationError(msg) corrected_current_point = flip_maximized_objective_values(problem, current_objective_vector) # calculate the weights weights = { obj.symbol: 1 / (nadir_point[obj.symbol] - (ideal_point[obj.symbol] - delta)) for obj in problem.objectives } # max term and constraints max_args = [] constraints = [] for i in range(len(classifications_list)): classifications = classifications_list[i] for obj in problem.objectives: _symbol = obj.symbol match classifications[_symbol]: case ("<", _): max_expr = f"{weights[_symbol]} * ({_symbol}_min - {ideal_point[_symbol]})" max_args.append(max_expr) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_lt", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("<=", aspiration): # if obj is to be maximized, then the current aspiration value needs to be multiplied by -1 max_expr = ( f"{weights[_symbol]} * ({_symbol}_min - {aspiration * -1 if obj.maximize else aspiration})" ) max_args.append(max_expr) con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"improvement until constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_lte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("=", _): con_expr = f"{_symbol}_min - {corrected_current_point[_symbol]}" constraints.append( Constraint( name=f"Stay at least as good constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_eq", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case (">=", reservation): # if obj is to be maximized, then the current reservation value needs to be multiplied by -1 con_expr = f"{_symbol}_min - {-1 * reservation if obj.maximize else reservation}" constraints.append( Constraint( name=f"Worsen until constraint for {_symbol}", symbol=f"{_symbol}_{i + 1}_gte", func=con_expr, cons_type=ConstraintTypeEnum.LTE, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) ) case ("0", _): # not relevant for this scalarization pass case (c, _): msg = ( f"Warning! The classification {c} was supplied, but it is not supported." "Must be one of ['<', '<=', '0', '=', '>=']" ) max_expr = f"Max({','.join(max_args)})" # form the augmentation term aug_exprs = [] for _ in range(len(classifications_list)): aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) func = f"{max_expr} + {rho} * ({aug_exprs})" scalarization = ScalarizationFunction( name="NIMBUS scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=False, ) _problem = problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ```` ### add_group_scenario_sf_diff ``` add_group_scenario_sf_diff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], weights: list[dict[str, float]], epsilon: float = 1e-06, ) -> tuple[Problem, str] ``` Add the differentiable scenario-based scalarization. Adds the following scalarization function: Parameters: | Name | Type | Description | Default | | ------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_points` | `list[dict[str, float]]` | a list of reference points as objective dicts. function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `weights` | `list[dict[str, float]]` | the list of weights to be used in the scalarization function. Must be positive. | *required* | | `epsilon` | `float` | small augmentation multiplier ε | `1e-06` | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_scenario_sf_diff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], weights: list[dict[str, float]], epsilon: float = 1e-6, ) -> tuple[Problem, str]: r"""Add the differentiable scenario-based scalarization. Adds the following scalarization function: \begin{align} \min_{x,\alpha}\quad & \alpha \;+\; \varepsilon \sum_{i,p} w_{ip}\bigl(f_{ip}(x) - \bar z_{ip}\bigr) \\ \text{s.t.}\quad & w_{ip}\bigl(f_{ip}(x) - \bar z_{ip}\bigr)\;-\;\alpha \;\le\;0 \quad\forall\,i,p,\\ & x \in \mathcal{X}\,, \end{align} Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_points (list[dict[str, float]]): a list of reference points as objective dicts. function symbols and values to reference point components, i.e., aspiration levels. weights (list[dict[str, float]]): the list of weights to be used in the scalarization function. Must be positive. epsilon: small augmentation multiplier ε Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ if len(reference_points) != len(weights): raise ScalarizationError("reference_points and weights must have same length") for idx, (ref_point, weight) in enumerate(zip(reference_points, weights, strict=True)): if not objective_dict_has_all_symbols(problem, ref_point): raise ScalarizationError(f"reference_points[{idx}] missing some objectives") if not objective_dict_has_all_symbols(problem, weight): raise ScalarizationError(f"weights[{idx}] missing some objectives") alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=0.0, ) sum_list = [] constraints = [] for idx, (ref_point, weight) in enumerate(zip(reference_points, weights, strict=True)): corrected_rp = flip_maximized_objective_values(problem, ref_point) for obj in problem.objectives: expr = f"{weight[obj.symbol]}*({obj.symbol}_min - {corrected_rp[obj.symbol]})" sum_list.append(expr) constraints.append( Constraint( name=f"ssf_con_{obj.symbol}", symbol=f"{obj.symbol}_con_{idx}", func=f"{expr} - {alpha.symbol}", cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) sum_part = " + ".join(sum_list) func = f"_alpha + {epsilon}*({sum_part})" scalar = ScalarizationFunction( name="Scenario-based differentiable ASF", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) problem_ = problem.add_variables([alpha]) problem_ = problem_.add_constraints(constraints) problem_ = problem_.add_scalarization(scalar) return problem_, symbol ``` ### add_group_scenario_sf_nondiff ``` add_group_scenario_sf_nondiff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], weights: list[dict[str, float]], epsilon: float = 1e-06, ) -> tuple[Problem, str] ``` Add the non-differentiable scenario based scalarization function. Add the following scalarization function: Parameters: | Name | Type | Description | Default | | ------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_points` | `list[dict[str, float]]` | a list of reference points as objective dicts. function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `weights` | `list[dict[str, float]]` | the list of weights to be used in the scalarization function. Must be positive. | *required* | | `epsilon` | `float` | small augmentation multiplier ε | `1e-06` | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_scenario_sf_nondiff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], weights: list[dict[str, float]], epsilon: float = 1e-6, ) -> tuple[Problem, str]: r"""Add the non-differentiable scenario based scalarization function. Add the following scalarization function: \begin{align} \min_{\mathbf{x}}\quad &\max_{i,p}\bigl[w_{ip}\bigl(f_{ip}(\mathbf{x}) - \bar z_{ip}\bigr)\bigr] \;+\;\varepsilon \sum_{i,p} w_{ip}\bigl(f_{ip}(\mathbf{x}) - \bar z_{ip}\bigr) \\[6pt] \text{s.t.}\quad &\mathbf{x} \in \mathcal{X}\,, \end{align} Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_points (list[dict[str, float]]): a list of reference points as objective dicts. function symbols and values to reference point components, i.e., aspiration levels. weights (list[dict[str, float]]): the list of weights to be used in the scalarization function. Must be positive. epsilon: small augmentation multiplier ε Returns: tuple[Problem, str]: A tuple containing a copy of the problem with the scalarization function added, and the symbol of the added scalarization function. """ if len(reference_points) != len(weights): raise ScalarizationError("reference_points and weights must have same length") for reference_point, weight in zip(reference_points, weights, strict=True): if not objective_dict_has_all_symbols(problem, reference_point): raise ScalarizationError( f"The give reference point {reference_point} is missing value for one or more objectives." ) if not objective_dict_has_all_symbols(problem, weight): raise ScalarizationError(f"The given weight vector {weight} is missing a value for one or more objectives.") max_list: list[str] = [] sum_list: list[str] = [] for reference_point, weight in zip(reference_points, weights, strict=True): corrected_ref_point = flip_maximized_objective_values(problem, reference_point) for obj in problem.objectives: expr = f"{weight[obj.symbol]}*({obj.symbol}_min - {corrected_ref_point[obj.symbol]})" max_list.append(expr) sum_list.append(expr) max_part = f"{Op.MAX}({', '.join(max_list)})" sum_part = " + ".join(sum_list) func = f"{max_part} + {epsilon}*({sum_part})" scalar = ScalarizationFunction( name="Group non differentiable scalarization function for scenario based problems.", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) return problem.add_scalarization(scalar), symbol ``` ### add_group_stom ``` add_group_stom( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the multiple decision maker variant of the STOM scalarizing function. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\max\_{i,d} \[w\_{id}(f\_{id}(\\mathbf{x})-z^{uto}_{id})\] + \\rho \\sum^k_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} &&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{\\overline{z}_{id} - z^{uto}_{id}}). Parameters: | Name | Type | Description | Default | | ------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_points` | `list[dict[str, float]]` | a list of dicts with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | `None` | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar value to define the utopian point. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_stom( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-6, ideal: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the multiple decision maker variant of the STOM scalarizing function. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\max_{i,d} [w_{id}(f_{id}(\mathbf{x})-z^{uto}_{id})] + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} &&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{\overline{z}_{id} - z^{uto}_{id}}$. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_points (list[dict[str, float]]): a list of dicts with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar value to define the utopian point. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check reference points for reference_point in reference_points: if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing value for one or more objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # calculate the weights weights = [] for reference_point in reference_points: corrected_rp = flip_maximized_objective_values(problem, reference_point) if type(delta) is dict: weights.append( { obj.symbol: 1 / ((corrected_rp[obj.symbol] - ideal_point[obj.symbol]) + delta[obj.symbol]) for obj in problem.objectives } ) else: weights.append( { obj.symbol: 1 / ((corrected_rp[obj.symbol] - ideal_point[obj.symbol]) + delta) for obj in problem.objectives } ) # form the max term max_terms = [] for i in range(len(reference_points)): for obj in problem.objectives: if type(delta) is dict: max_terms.append( f"{weights[i][obj.symbol]} * ({obj.symbol}_min - {ideal_point[obj.symbol] - delta[obj.symbol]})" ) else: max_terms.append(f"{weights[i][obj.symbol]} * ({obj.symbol}_min - {ideal_point[obj.symbol] - delta})") max_terms = ", ".join(max_terms) # form the augmentation term aug_exprs = [] for i in range(len(reference_points)): aug_expr = " + ".join([f"({weights[i][obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) func = f"{Op.MAX}({max_terms}) + {rho}*({aug_exprs})" scalarization_function = ScalarizationFunction( name="STOM scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=False, ) problem = problem.add_scalarization(scalarization_function) # get corrected bounds if exist if agg_bounds is not None: bounds = flip_maximized_objective_values(problem, agg_bounds) constraints = [] for obj in problem.objectives: expr = f"({obj.symbol}_min - {bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) problem = problem.add_constraints(constraints) return problem, symbol ``` ### add_group_stom_agg ``` add_group_stom_agg( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the multiple decision maker variant of the STOM scalarizing function. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} &&\\max\_{i,d} \[w\_{id}(f\_{id}(\\mathbf{x})-z^{uto}_{id})\] + \\rho \\sum^k_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} &&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{\\overline{z}_{id} - z^{uto}_{id}}). Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `agg_aspirations` | `dict[str, float]` | a dictionary of aggregated aspiration levels, i.e., min aspirations. | *required* | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar value to define the utopian point. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_stom_agg( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float], delta: dict[str, float] | float = 1e-6, ideal: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the multiple decision maker variant of the STOM scalarizing function. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} &&\max_{i,d} [w_{id}(f_{id}(\mathbf{x})-z^{uto}_{id})] + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} &&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{\overline{z}_{id} - z^{uto}_{id}}$. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. agg_aspirations (dict[str, float]): a dictionary of aggregated aspiration levels, i.e., min aspirations. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar value to define the utopian point. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # Correct the aspirations and hard_constraints agg_aspirations = flip_maximized_objective_values(problem, agg_aspirations) agg_bounds = flip_maximized_objective_values(problem, agg_bounds) # calculate the weights weights = None if type(delta) is dict: weights = { obj.symbol: 1 / ((agg_aspirations[obj.symbol] - ideal_point[obj.symbol]) + delta[obj.symbol]) for obj in problem.objectives } else: weights = { obj.symbol: 1 / ((agg_aspirations[obj.symbol] - ideal_point[obj.symbol]) + delta) for obj in problem.objectives } # form the max and augmentation terms max_terms = [] aug_exprs = [] for obj in problem.objectives: if type(delta) is dict: max_terms.append( f"({weights[obj.symbol]}) * ({obj.symbol}_min - {ideal_point[obj.symbol] - delta[obj.symbol]} )" ) else: max_terms.append(f"{weights[obj.symbol]} * ({obj.symbol}_min - {ideal_point[obj.symbol] - delta})") aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) max_terms = ", ".join(max_terms) aug_exprs = " + ".join(aug_exprs) func = f"{Op.MAX}({max_terms}) + {rho} * ({aug_exprs})" scalarization_function = ScalarizationFunction( name="STOM scalarizing function for multiple decision makers", symbol=symbol, func=func, is_convex=problem.is_convex, is_linear=problem.is_linear, is_twice_differentiable=False, ) constraints = [] for obj in problem.objectives: expr = f"({obj.symbol}_min - {agg_bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) problem = problem.add_constraints(constraints) problem = problem.add_scalarization(scalarization_function) return problem, symbol ``` ### add_group_stom_agg_diff ``` add_group_stom_agg_diff( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the differentiable variant of the multiple decision maker variant of the STOM scalarizing function. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} && \\alpha + \\rho \\sum^k\_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} && w\_{id}(f\_{id}(\\mathbf{x})-z^{uto}\_{id}) - \\alpha \\leq 0,\\ &&&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{\\overline{z}_{id} - z^{uto}_{id}}). Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `agg_aspirations` | `dict[str, float]` | a dictionary of aggregated aspiration levels, i.e., min aspirations. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar value to define the utopian point. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_stom_agg_diff( problem: Problem, symbol: str, agg_aspirations: dict[str, float], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-6, ideal: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the differentiable variant of the multiple decision maker variant of the STOM scalarizing function. Both aggregated aspiration levels (min aspirations) and agg bounds (max bounds) are required. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} && \alpha + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} && w_{id}(f_{id}(\mathbf{x})-z^{uto}_{id}) - \alpha \leq 0,\\ &&&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{\overline{z}_{id} - z^{uto}_{id}}$. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. agg_aspirations (dict[str, float]): a dictionary of aggregated aspiration levels, i.e., min aspirations. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar value to define the utopian point. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # Correct the aspirations and hard_constraints agg_aspirations = flip_maximized_objective_values(problem, agg_aspirations) # calculate the weights weights = {} if type(delta) is dict: weights = { obj.symbol: 1 / ((agg_aspirations[obj.symbol] - ideal_point[obj.symbol]) + delta[obj.symbol]) for obj in problem.objectives } else: weights = { obj.symbol: 1 / ((agg_aspirations[obj.symbol] - ideal_point[obj.symbol]) + delta) for obj in problem.objectives } # form the max term con_terms = [] for obj in problem.objectives: if type(delta) is dict: con_terms.append( f"{weights[obj.symbol]} * ({obj.symbol}_min - {ideal_point[obj.symbol] - delta[obj.symbol]}) - _alpha" ) else: con_terms.append(f"{weights[obj.symbol]} * ({obj.symbol}_min - {ideal_point[obj.symbol] - delta}) - _alpha") # form the augmentation term aug_exprs = [] aug_expr = " + ".join([f"({weights[obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) constraints = [] # loop to create a constraint for every objective of every reference point given for obj in problem.objectives: if type(delta) is dict: expr = ( f"({obj.symbol}_min - {ideal_point[obj.symbol] - delta[obj.symbol]}) / " f"({agg_aspirations[obj.symbol] - (ideal_point[obj.symbol] - delta[obj.symbol])}) - _alpha" ) else: expr = ( f"({obj.symbol}_min - {ideal_point[obj.symbol] - delta}) / " f"({agg_aspirations[obj.symbol] - (ideal_point[obj.symbol] - delta)}) - _alpha" ) constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_maxcon", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) # get corrected bounds if exist if agg_bounds is not None: bounds = flip_maximized_objective_values(problem, agg_bounds) for obj in problem.objectives: expr = f"({obj.symbol}_min - {bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) func = f"_alpha + {rho}*({aug_exprs})" scalarization = ScalarizationFunction( name="Differentiable STOM scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ### add_group_stom_diff ``` add_group_stom_diff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-06, ideal: dict[str, float] | None = None, rho: float = 1e-06, ) -> tuple[Problem, str] ``` Adds the differentiable variant of the multiple decision maker variant of the STOM scalarizing function. The scalarization function is defined as follows: \[\\begin{align} &\\mbox{minimize} && \\alpha + \\rho \\sum^k\_{i=1} \\sum^{n_d}_{d=1} w_{id}f\_{id}(\\mathbf{x}) \\ &\\mbox{subject to} && w\_{id}(f\_{id}(\\mathbf{x})-z^{uto}\_{id}) - \\alpha \\leq 0,\\ &&&\\mathbf{x} \\in \\mathbf{X}, \\end{align}\] where (w\_{id} = \\frac{1}{\\overline{z}_{id} - z^{uto}_{id}}). Parameters: | Name | Type | Description | Default | | ------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem the scalarization is added to. | *required* | | `symbol` | `str` | the symbol given to the added scalarization. | *required* | | `reference_points` | `list[dict[str, float]]` | a list of dicts with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. | *required* | | `ideal` | `dict[str, float]` | ideal point values. If not given, attempt will be made to calculate ideal point from problem. | `None` | | `agg_bounds` | `dict[str, float]` | a dictionary of bounds not to violate. | `None` | | `rho` | `float` | a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. | `1e-06` | | `delta` | `float` | a small scalar value to define the utopian point. Defaults to 1e-6. | `1e-06` | Raises: | Type | Description | | -------------------- | -------------------------------------------------- | | `ScalarizationError` | there are missing elements in any reference point. | Returns: | Type | Description | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `tuple[Problem, str]` | tuple\[Problem, str\]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. | Source code in `desdeo/tools/group_scalarization.py` ``` def add_group_stom_diff( problem: Problem, symbol: str, reference_points: list[dict[str, float]], agg_bounds: dict[str, float] | None = None, delta: dict[str, float] | float = 1e-6, ideal: dict[str, float] | None = None, rho: float = 1e-6, ) -> tuple[Problem, str]: r"""Adds the differentiable variant of the multiple decision maker variant of the STOM scalarizing function. The scalarization function is defined as follows: \begin{align} &\mbox{minimize} && \alpha + \rho \sum^k_{i=1} \sum^{n_d}_{d=1} w_{id}f_{id}(\mathbf{x}) \\ &\mbox{subject to} && w_{id}(f_{id}(\mathbf{x})-z^{uto}_{id}) - \alpha \leq 0,\\ &&&\mathbf{x} \in \mathbf{X}, \end{align} where $w_{id} = \frac{1}{\overline{z}_{id} - z^{uto}_{id}}$. Args: problem (Problem): the problem the scalarization is added to. symbol (str): the symbol given to the added scalarization. reference_points (list[dict[str, float]]): a list of dicts with keys corresponding to objective function symbols and values to reference point components, i.e., aspiration levels. ideal (dict[str, float], optional): ideal point values. If not given, attempt will be made to calculate ideal point from problem. agg_bounds (dict[str, float]): a dictionary of bounds not to violate. rho (float, optional): a small scalar value to scale the sum in the objective function of the scalarization. Defaults to 1e-6. delta (float, optional): a small scalar value to define the utopian point. Defaults to 1e-6. Raises: ScalarizationError: there are missing elements in any reference point. Returns: tuple[Problem, str]: a tuple with the copy of the problem with the added scalarization and the symbol of the added scalarization. """ # check reference points for reference_point in reference_points: if not objective_dict_has_all_symbols(problem, reference_point): msg = f"The give reference point {reference_point} is missing value for one or more objectives." raise ScalarizationError(msg) # check if ideal point is specified # if not specified, try to calculate corrected ideal point if ideal is not None: ideal_point = ideal elif problem.get_ideal_point() is not None: ideal_point = get_corrected_ideal(problem) else: msg = "Ideal point not defined!" raise ScalarizationError(msg) # define the auxiliary variable alpha = Variable( name="alpha", symbol="_alpha", variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=1.0, ) # calculate the weights weights = [] for reference_point in reference_points: corrected_rp = flip_maximized_objective_values(problem, reference_point) if type(delta) is dict: weights.append( { obj.symbol: 1 / ((corrected_rp[obj.symbol] - ideal_point[obj.symbol]) + delta[obj.symbol]) for obj in problem.objectives } ) else: weights.append( { obj.symbol: 1 / ((corrected_rp[obj.symbol] - ideal_point[obj.symbol]) + delta) for obj in problem.objectives } ) # form the max term con_terms = [] for i in range(len(reference_points)): rp = {} for obj in problem.objectives: if type(delta) is dict: rp[obj.symbol] = ( f"{weights[i][obj.symbol]} * ({obj.symbol}_min - {ideal_point[obj.symbol] - delta[obj.symbol]})" " - _alpha" ) else: rp[obj.symbol] = ( f"{weights[i][obj.symbol]} * ({obj.symbol}_min - {ideal_point[obj.symbol] - delta}) - _alpha" ) con_terms.append(rp) # form the augmentation term aug_exprs = [] for i in range(len(reference_points)): aug_expr = " + ".join([f"({weights[i][obj.symbol]} * {obj.symbol}_min)" for obj in problem.objectives]) aug_exprs.append(aug_expr) aug_exprs = " + ".join(aug_exprs) constraints = [] # loop to create a constraint for every objective of every reference point given for i in range(len(reference_points)): for obj in problem.objectives: # since we are subtracting a constant value, the linearity, convexity, # and differentiability of the objective function, and hence the # constraint, should not change. constraints.append( Constraint( name=f"Constraint for {obj.symbol}", symbol=f"{obj.symbol}_con_{i + 1}", func=con_terms[i][obj.symbol], cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) # get corrected bounds if exist if agg_bounds is not None: bounds = flip_maximized_objective_values(problem, agg_bounds) for obj in problem.objectives: expr = f"({obj.symbol}_min - {bounds[obj.symbol]})" constraints.append( Constraint( name=f"Constraint bound for {obj.symbol}", symbol=f"{obj.symbol}_con", func=expr, cons_type=ConstraintTypeEnum.LTE, is_linear=obj.is_linear, is_convex=obj.is_convex, is_twice_differentiable=obj.is_twice_differentiable, ) ) func = f"_alpha + {rho}*({aug_exprs})" scalarization = ScalarizationFunction( name="Differentiable STOM scalarization objective function for multiple decision makers", symbol=symbol, func=func, is_linear=problem.is_linear, is_convex=problem.is_convex, is_twice_differentiable=problem.is_twice_differentiable, ) _problem = problem.add_variables([alpha]) _problem = _problem.add_scalarization(scalarization) return _problem.add_constraints(constraints), symbol ``` ## Gurobipy solver interfaces Defines solver interfaces for gurobipy. ### GurobipySolver Bases: `BaseSolver` Creates a gurobipy solver that utilizes gurobi's own Python implementation. Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` class GurobipySolver(BaseSolver): """Creates a gurobipy solver that utilizes gurobi's own Python implementation.""" def __init__(self, problem: Problem, options: dict[str, any] | None = None): """The solver is initialized by supplying a problem and options. Unlike with Pyomo you do not need to have gurobi installed on your system for this to work. Suitable for solving mixed-integer linear and quadratic optimization problems. Args: problem (Problem): the problem to be solved. options (dict[str,any]): Dictionary of Gurobi parameters to set. You probably don't need to set any of these and can just use the defaults. For available parameters see https://www.gurobi.com/documentation/current/refman/parameters.html """ self.evaluator = GurobipyEvaluator(problem) self.problem = problem if options is not None: for key, value in options.items(): self.evaluator.model.setParam(key, value) else: # Set some default parameters that are good for most problems. self.evaluator.model.setParam("OutputFlag", 0) # Suppress Gurobi output self.evaluator.model.setParam("LogToConsole", 0) # Suppress Gurobi logging to console def solve(self, target: str) -> SolverResults: """Solve the problem for the given target. Args: target (str): the symbol of the function to be optimized, and which is defined in the problem given when initializing the solver. Returns: SolverResults: the results of the optimization. """ self.evaluator.set_optimization_target(target) self.evaluator.model.optimize() return parse_gurobipy_optimizer_results(self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: dict[str, any] | None = None ) ``` The solver is initialized by supplying a problem and options. Unlike with Pyomo you do not need to have gurobi installed on your system for this to work. Suitable for solving mixed-integer linear and quadratic optimization problems. Parameters: | Name | Type | Description | Default | | --------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to be solved. | *required* | | `options` | `dict[str, any]` | Dictionary of Gurobi parameters to set. You probably don't need to set any of these and can just use the defaults. For available parameters see https://www.gurobi.com/documentation/current/refman/parameters.html | `None` | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def __init__(self, problem: Problem, options: dict[str, any] | None = None): """The solver is initialized by supplying a problem and options. Unlike with Pyomo you do not need to have gurobi installed on your system for this to work. Suitable for solving mixed-integer linear and quadratic optimization problems. Args: problem (Problem): the problem to be solved. options (dict[str,any]): Dictionary of Gurobi parameters to set. You probably don't need to set any of these and can just use the defaults. For available parameters see https://www.gurobi.com/documentation/current/refman/parameters.html """ self.evaluator = GurobipyEvaluator(problem) self.problem = problem if options is not None: for key, value in options.items(): self.evaluator.model.setParam(key, value) else: # Set some default parameters that are good for most problems. self.evaluator.model.setParam("OutputFlag", 0) # Suppress Gurobi output self.evaluator.model.setParam("LogToConsole", 0) # Suppress Gurobi logging to console ``` #### solve ``` solve(target: str) -> SolverResults ``` Solve the problem for the given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ------------------------------------------------------------------------------------------------------------------- | ---------- | | `target` | `str` | the symbol of the function to be optimized, and which is defined in the problem given when initializing the solver. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | -------------------------------- | | `SolverResults` | `SolverResults` | the results of the optimization. | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solve the problem for the given target. Args: target (str): the symbol of the function to be optimized, and which is defined in the problem given when initializing the solver. Returns: SolverResults: the results of the optimization. """ self.evaluator.set_optimization_target(target) self.evaluator.model.optimize() return parse_gurobipy_optimizer_results(self.problem, self.evaluator) ``` ### PersistentGurobipySolver Bases: `PersistentSolver` A persistent solver class utlizing gurobipy. Use this instead of create_gurobipy_solver when re-initializing the solver every time the problem is changed is not practical. Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` class PersistentGurobipySolver(PersistentSolver): """A persistent solver class utlizing gurobipy. Use this instead of create_gurobipy_solver when re-initializing the solver every time the problem is changed is not practical. """ evaluator: GurobipyEvaluator def __init__(self, problem: Problem, options: dict[str, any] | None = None): """Initializer for the persistent solver. Args: problem (Problem): the problem to be transformed in a GurobipyModel. options (dict[str,any]): Dictionary of Gurobi parameters to set. You probably don't need to set any of these and can just use the defaults. For available parameters see https://www.gurobi.com/documentation/current/refman/parameters.html """ self.problem = problem self.evaluator = GurobipyEvaluator(problem) if options is not None: for key, value in options.items(): self.evaluator.model.setParam(key, value) def add_constraint(self, constraint: Constraint | list[Constraint]) -> gp.Constr | list[gp.Constr]: """Add one or more constraint expressions to the solver. If adding a lot of constraints or dealing with a large model, this function may end up being very slow compared to adding the constraints to the model stored in the evaluator directly. Args: constraint (Constraint): the constraint function expression or a list of constraint function expressions. Raises: GurobipyEvaluatorError: when an unsupported constraint type is encountered. Returns: gurobipy.Constr: The gurobipy constraint that was added or a list of gurobipy constraints if the constraint argument was a list. """ if isinstance(constraint, list): cons_list = list[gp.Constr] for cons in constraint: cons_list.append(self.evaluator.add_constraint(cons)) return cons_list return self.evaluator.add_constraint(constraint) def add_objective(self, objective: Objective | list[Objective]): """Adds an objective function expression to the solver. Does not yet add any actual gurobipy optimization objectives, only adds them to the dict containing the expressions of the objectives. The objective expressions are stored in the evaluator and the evaluator must add the appropiate gurobipy objective before solving. Args: objective (Objective): an objective function expression or a list of objective function expressions to be added. """ if not isinstance(objective, list): objective = [objective] for obj in objective: self.evaluator.add_objective(obj) def add_scalarization_function(self, scalarization: ScalarizationFunction | list[ScalarizationFunction]): """Adds a scalrization expression to the solver. Scalarizations work identically to objectives, except they are stored in a different dict in the evaluator. If you want to solve the problem using a scalarization, the evaluator needs to set it as an optimization target first. Args: scalarization (ScalarizationFunction): A scalarization function or a list of scalarization functions to be added. """ if not isinstance(scalarization, list): scalarization = [scalarization] for scal in scalarization: self.evaluator.add_scalarization_function(scal) def add_variable( self, variable: Variable | TensorVariable | list[Variable] | list[TensorVariable] ) -> gp.Var | gp.MVar | list[gp.Var] | list[gp.MVar]: """Add one or more variables to the solver. If adding a lot of variables or dealing with a large model, this function may end up being very slow compared to adding the variables to the model stored in the evaluator directly. Args: variable (Variable): The definition of the variable or a list of variables to be added. Raises: GurobipyEvaluatorError: when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. Returns: gp.Var: the variable that was added to the model or a list of variables if variable argument was a list. """ if isinstance(variable, list): var_list = list[gp.Var | gp.MVar] for var in variable: var_list.append(self.evaluator.add_variable(var)) return var_list return self.evaluator.add_variable(variable) def remove_constraint(self, symbol: str | list[str]): """Removes a constraint from the solver. If removing a lot of constraints or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the model stored in the evaluator directly may be faster. Args: symbol (str): a str representing the symbol of the constraint to be removed. Can also be a list of multiple symbols. """ if not isinstance(symbol, list): symbol = [symbol] for s in symbol: self.evaluator.remove_constraint(s) def remove_variable(self, symbol: str | list[str]): """Removes a variable from the model. If removing a lot of variables or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the model stored in the evaluator directly may be faster. Args: symbol (str): a str representing the symbol of the variable to be removed. Can also be a list of multiple symbols. """ self.evaluator.remove_variable(symbol) def solve(self, target: str) -> SolverResults: """Solves the current problem with the specified target. Args: target (str): a str representing the symbol of the target function. Returns: SolverResults: The results of the solver """ self.evaluator.set_optimization_target(target) self.evaluator.model.optimize() return parse_gurobipy_optimizer_results(self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: dict[str, any] | None = None ) ``` Initializer for the persistent solver. Parameters: | Name | Type | Description | Default | | --------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to be transformed in a GurobipyModel. | *required* | | `options` | `dict[str, any]` | Dictionary of Gurobi parameters to set. You probably don't need to set any of these and can just use the defaults. For available parameters see https://www.gurobi.com/documentation/current/refman/parameters.html | `None` | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def __init__(self, problem: Problem, options: dict[str, any] | None = None): """Initializer for the persistent solver. Args: problem (Problem): the problem to be transformed in a GurobipyModel. options (dict[str,any]): Dictionary of Gurobi parameters to set. You probably don't need to set any of these and can just use the defaults. For available parameters see https://www.gurobi.com/documentation/current/refman/parameters.html """ self.problem = problem self.evaluator = GurobipyEvaluator(problem) if options is not None: for key, value in options.items(): self.evaluator.model.setParam(key, value) ``` #### add_constraint ``` add_constraint( constraint: Constraint | list[Constraint], ) -> gp.Constr | list[gp.Constr] ``` Add one or more constraint expressions to the solver. If adding a lot of constraints or dealing with a large model, this function may end up being very slow compared to adding the constraints to the model stored in the evaluator directly. Parameters: | Name | Type | Description | Default | | ------------ | ------------ | -------------------------------------------------------------------------------- | ---------- | | `constraint` | `Constraint` | the constraint function expression or a list of constraint function expressions. | *required* | Raises: | Type | Description | | ------------------------ | --------------------------------------------------- | | `GurobipyEvaluatorError` | when an unsupported constraint type is encountered. | Returns: | Type | Description | | -------- | -------------- | | \`Constr | list[Constr]\` | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def add_constraint(self, constraint: Constraint | list[Constraint]) -> gp.Constr | list[gp.Constr]: """Add one or more constraint expressions to the solver. If adding a lot of constraints or dealing with a large model, this function may end up being very slow compared to adding the constraints to the model stored in the evaluator directly. Args: constraint (Constraint): the constraint function expression or a list of constraint function expressions. Raises: GurobipyEvaluatorError: when an unsupported constraint type is encountered. Returns: gurobipy.Constr: The gurobipy constraint that was added or a list of gurobipy constraints if the constraint argument was a list. """ if isinstance(constraint, list): cons_list = list[gp.Constr] for cons in constraint: cons_list.append(self.evaluator.add_constraint(cons)) return cons_list return self.evaluator.add_constraint(constraint) ``` #### add_objective ``` add_objective(objective: Objective | list[Objective]) ``` Adds an objective function expression to the solver. Does not yet add any actual gurobipy optimization objectives, only adds them to the dict containing the expressions of the objectives. The objective expressions are stored in the evaluator and the evaluator must add the appropiate gurobipy objective before solving. Parameters: | Name | Type | Description | Default | | ----------- | ----------- | ----------------------------------------------------------------------------------------- | ---------- | | `objective` | `Objective` | an objective function expression or a list of objective function expressions to be added. | *required* | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def add_objective(self, objective: Objective | list[Objective]): """Adds an objective function expression to the solver. Does not yet add any actual gurobipy optimization objectives, only adds them to the dict containing the expressions of the objectives. The objective expressions are stored in the evaluator and the evaluator must add the appropiate gurobipy objective before solving. Args: objective (Objective): an objective function expression or a list of objective function expressions to be added. """ if not isinstance(objective, list): objective = [objective] for obj in objective: self.evaluator.add_objective(obj) ``` #### add_scalarization_function ``` add_scalarization_function( scalarization: ScalarizationFunction | list[ScalarizationFunction], ) ``` Adds a scalrization expression to the solver. Scalarizations work identically to objectives, except they are stored in a different dict in the evaluator. If you want to solve the problem using a scalarization, the evaluator needs to set it as an optimization target first. Parameters: | Name | Type | Description | Default | | --------------- | ----------------------- | -------------------------------------------------------------------------- | ---------- | | `scalarization` | `ScalarizationFunction` | A scalarization function or a list of scalarization functions to be added. | *required* | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def add_scalarization_function(self, scalarization: ScalarizationFunction | list[ScalarizationFunction]): """Adds a scalrization expression to the solver. Scalarizations work identically to objectives, except they are stored in a different dict in the evaluator. If you want to solve the problem using a scalarization, the evaluator needs to set it as an optimization target first. Args: scalarization (ScalarizationFunction): A scalarization function or a list of scalarization functions to be added. """ if not isinstance(scalarization, list): scalarization = [scalarization] for scal in scalarization: self.evaluator.add_scalarization_function(scal) ``` #### add_variable ``` add_variable( variable: Variable | TensorVariable | list[Variable] | list[TensorVariable], ) -> gp.Var | gp.MVar | list[gp.Var] | list[gp.MVar] ``` Add one or more variables to the solver. If adding a lot of variables or dealing with a large model, this function may end up being very slow compared to adding the variables to the model stored in the evaluator directly. Parameters: | Name | Type | Description | Default | | ---------- | ---------- | ------------------------------------------------------------------ | ---------- | | `variable` | `Variable` | The definition of the variable or a list of variables to be added. | *required* | Raises: | Type | Description | | ------------------------ | ----------------------------------------------------------------------------------------------------------- | | `GurobipyEvaluatorError` | when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. | Returns: | Type | Description | | ----- | ----------- | | \`Var | MVar | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def add_variable( self, variable: Variable | TensorVariable | list[Variable] | list[TensorVariable] ) -> gp.Var | gp.MVar | list[gp.Var] | list[gp.MVar]: """Add one or more variables to the solver. If adding a lot of variables or dealing with a large model, this function may end up being very slow compared to adding the variables to the model stored in the evaluator directly. Args: variable (Variable): The definition of the variable or a list of variables to be added. Raises: GurobipyEvaluatorError: when a problem in extracting the variables is encountered. I.e., the variables are of a non supported type. Returns: gp.Var: the variable that was added to the model or a list of variables if variable argument was a list. """ if isinstance(variable, list): var_list = list[gp.Var | gp.MVar] for var in variable: var_list.append(self.evaluator.add_variable(var)) return var_list return self.evaluator.add_variable(variable) ``` #### remove_constraint ``` remove_constraint(symbol: str | list[str]) ``` Removes a constraint from the solver. If removing a lot of constraints or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the model stored in the evaluator directly may be faster. Parameters: | Name | Type | Description | Default | | -------- | ----- | ------------------------------------------------------------------------------------------------------ | ---------- | | `symbol` | `str` | a str representing the symbol of the constraint to be removed. Can also be a list of multiple symbols. | *required* | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def remove_constraint(self, symbol: str | list[str]): """Removes a constraint from the solver. If removing a lot of constraints or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the model stored in the evaluator directly may be faster. Args: symbol (str): a str representing the symbol of the constraint to be removed. Can also be a list of multiple symbols. """ if not isinstance(symbol, list): symbol = [symbol] for s in symbol: self.evaluator.remove_constraint(s) ``` #### remove_variable ``` remove_variable(symbol: str | list[str]) ``` Removes a variable from the model. If removing a lot of variables or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the model stored in the evaluator directly may be faster. Parameters: | Name | Type | Description | Default | | -------- | ----- | ---------------------------------------------------------------------------------------------------- | ---------- | | `symbol` | `str` | a str representing the symbol of the variable to be removed. Can also be a list of multiple symbols. | *required* | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def remove_variable(self, symbol: str | list[str]): """Removes a variable from the model. If removing a lot of variables or dealing with a very large model this function may be slow because of the model.update() calls. Accessing the model stored in the evaluator directly may be faster. Args: symbol (str): a str representing the symbol of the variable to be removed. Can also be a list of multiple symbols. """ self.evaluator.remove_variable(symbol) ``` #### solve ``` solve(target: str) -> SolverResults ``` Solves the current problem with the specified target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | a str representing the symbol of the target function. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ------------------------- | | `SolverResults` | `SolverResults` | The results of the solver | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solves the current problem with the specified target. Args: target (str): a str representing the symbol of the target function. Returns: SolverResults: The results of the solver """ self.evaluator.set_optimization_target(target) self.evaluator.model.optimize() return parse_gurobipy_optimizer_results(self.problem, self.evaluator) ``` ### \_constraint_contains_objective ``` _constraint_contains_objective( constraint: Constraint, objective_symbol: str ) -> bool ``` Check if a constraint's function contains a specific objective symbol. Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def _constraint_contains_objective(constraint: Constraint, objective_symbol: str) -> bool: """Check if a constraint's function contains a specific objective symbol.""" func_str = str(constraint.func) return objective_symbol in func_str ``` ### check_gurobi_license ``` check_gurobi_license() ``` Check if Gurobi is using a full license (not trial). Returns: | Type | Description | | ----- | ----------- | | \`str | bool\` | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def check_gurobi_license(): """Check if Gurobi is using a full license (not trial). Returns: (str | bool): True if using full academic/commercial license False if using trial license or no license found """ captured_output = io.StringIO() original_stdout = sys.stdout try: sys.stdout = captured_output with gp.Env(empty=True) as env: env.setParam("OutputFlag", 1) env.start() sys.stdout = original_stdout output = captured_output.getvalue() return "Restricted license - for non-production use only" not in output # noqa: TRY300 except Exception: sys.stdout = original_stdout return False ``` ### parse_gurobipy_optimizer_results ``` parse_gurobipy_optimizer_results( problem: Problem, evaluator: GurobipyEvaluator ) -> SolverResults ``` Parses results from GurobipyEvaluator's model into DESDEO SolverResults. Parameters: | Name | Type | Description | Default | | ----------- | ------------------- | -------------------------------------------- | ---------- | | `problem` | `Problem` | the problem being solved. | *required* | | `evaluator` | `GurobipyEvaluator` | the evaluator utilized to solve the problem. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ---------------------- | | `SolverResults` | `SolverResults` | DESDEO solver results. | Source code in `desdeo/tools/gurobipy_solver_interfaces.py` ``` def parse_gurobipy_optimizer_results(problem: Problem, evaluator: GurobipyEvaluator) -> SolverResults: """Parses results from GurobipyEvaluator's model into DESDEO SolverResults. Args: problem (Problem): the problem being solved. evaluator (GurobipyEvaluator): the evaluator utilized to solve the problem. Returns: SolverResults: DESDEO solver results. """ model_status = evaluator.model.status success = model_status == gp.GRB.OPTIMAL if model_status == gp.GRB.OPTIMAL: status = "Optimal solution found." elif model_status == gp.GRB.INFEASIBLE: status = "Model is infeasible." elif model_status == gp.GRB.UNBOUNDED: status = "Model is unbounded." elif model_status == gp.GRB.INF_OR_UNBD: status = "Model is either infeasible or unbounded." else: status = f"Optimization ended with status: {model_status}" msg = f"Gurobipy solver status is: '{status}'" if not success: return SolverResults( optimal_variables={var.symbol: float("nan") for var in problem.variables}, optimal_objectives={obj.symbol: float("nan") for obj in problem.objectives}, constraint_values=None, extra_func_values=None, scalarization_values=None, lagrange_multipliers=None, success=False, message=msg, ) results = evaluator.get_values() variable_values = {var.symbol: results[var.symbol] for var in problem.variables} objective_values = {obj.symbol: results[obj.symbol] for obj in problem.objectives} constraint_values = ( {con.symbol: results[con.symbol] for con in problem.constraints} if problem.constraints is not None else None ) extra_func_values = ( {extra.symbol: results[extra.symbol] for extra in problem.extra_funcs} if problem.extra_funcs is not None else None ) scalarization_values = ( {scal.symbol: results[scal.symbol] for scal in problem.scalarization_funcs} if problem.scalarization_funcs is not None else None ) lagrange_multipliers = None if problem.constraints is not None: objective_symbols = set(objective_values.keys()) lagrange_multipliers = { con.symbol: results[con.symbol] for con in problem.constraints if any(obj_sym in con.symbol for obj_sym in objective_symbols) } return SolverResults( optimal_variables=variable_values, optimal_objectives=objective_values, constraint_values=constraint_values, extra_func_values=extra_func_values, scalarization_values=scalarization_values, lagrange_multipliers=lagrange_multipliers, success=True, message=msg, ) ``` ## CVXPY solver interfaces Defines solver interfaces for cvxpy. ### CVXPYSolver Bases: `BaseSolver` Creates a CVXPY solver that utilizes CVXPY's optimization capabilities. Source code in `desdeo/tools/cvxpy_solver_interfaces.py` ``` class CVXPYSolver(BaseSolver): """Creates a CVXPY solver that utilizes CVXPY's optimization capabilities.""" def __init__(self, problem: Problem, options: CVXPYSolverOptions | None = _default_cvxpy_options): """The solver is initialized by supplying a problem and options. CVXPY is a Python-embedded modeling language for convex optimization problems, supporting a broad range of problem types. Args: problem (Problem): the problem to be solved. options (CVXPYSolverOptions | None): Pydantic model containing solver options for CVXPY. For available options see https://www.cvxpy.org/api_reference/cvxpy.problems.html#solve If `None` is passed, defaults to `_default_cvxpy_options` defined in this source file. """ self.evaluator = CVXPYEvaluator(problem) self.problem = problem if options is None: options = _default_cvxpy_options options_dict = {k: v for k, v in options.model_dump().items() if v is not None} extra_options = options_dict.pop("extra_options", None) if extra_options is not None: options_dict.update(extra_options) self.solve_options = options_dict def solve(self, target: str) -> SolverResults: """Solve the problem for the given target. Args: target (str): the symbol of the function to be optimized, and which is defined in the problem given when initializing the solver. Returns: SolverResults: the results of the optimization. """ self.evaluator.set_optimization_target(target) self.evaluator.solve(**self.solve_options) return parse_cvxpy_optimizer_results(self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: CVXPYSolverOptions | None = _default_cvxpy_options, ) ``` The solver is initialized by supplying a problem and options. CVXPY is a Python-embedded modeling language for convex optimization problems, supporting a broad range of problem types. Parameters: | Name | Type | Description | Default | | --------- | -------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to be solved. | *required* | | `options` | \`CVXPYSolverOptions | None\` | Pydantic model containing solver options for CVXPY. For available options see https://www.cvxpy.org/api_reference/cvxpy.problems.html#solve If None is passed, defaults to \_default_cvxpy_options defined in this source file. | Source code in `desdeo/tools/cvxpy_solver_interfaces.py` ``` def __init__(self, problem: Problem, options: CVXPYSolverOptions | None = _default_cvxpy_options): """The solver is initialized by supplying a problem and options. CVXPY is a Python-embedded modeling language for convex optimization problems, supporting a broad range of problem types. Args: problem (Problem): the problem to be solved. options (CVXPYSolverOptions | None): Pydantic model containing solver options for CVXPY. For available options see https://www.cvxpy.org/api_reference/cvxpy.problems.html#solve If `None` is passed, defaults to `_default_cvxpy_options` defined in this source file. """ self.evaluator = CVXPYEvaluator(problem) self.problem = problem if options is None: options = _default_cvxpy_options options_dict = {k: v for k, v in options.model_dump().items() if v is not None} extra_options = options_dict.pop("extra_options", None) if extra_options is not None: options_dict.update(extra_options) self.solve_options = options_dict ``` #### solve ``` solve(target: str) -> SolverResults ``` Solve the problem for the given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ------------------------------------------------------------------------------------------------------------------- | ---------- | | `target` | `str` | the symbol of the function to be optimized, and which is defined in the problem given when initializing the solver. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | -------------------------------- | | `SolverResults` | `SolverResults` | the results of the optimization. | Source code in `desdeo/tools/cvxpy_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solve the problem for the given target. Args: target (str): the symbol of the function to be optimized, and which is defined in the problem given when initializing the solver. Returns: SolverResults: the results of the optimization. """ self.evaluator.set_optimization_target(target) self.evaluator.solve(**self.solve_options) return parse_cvxpy_optimizer_results(self.problem, self.evaluator) ``` ### CVXPYSolverOptions Bases: `BaseModel` Defines a pydantic model to store and pass options to the CVXPY solver. Source code in `desdeo/tools/cvxpy_solver_interfaces.py` ``` class CVXPYSolverOptions(BaseModel): """Defines a pydantic model to store and pass options to the CVXPY solver.""" solver: str | None = Field( description="The solver to use.", default=None, ) solver_path: list[str | tuple[str, dict[str, object]]] | None = Field( description="The solvers to try with optional arguments, in order of preference.", default=None, ) verbose: bool = Field(description="Overrides the default of hiding solver output.", default=False) gp: bool = Field(description="Parse the problem as a disciplined geometric program.", default=False) qcp: bool = Field(description="Parse the problem as a disciplined quasiconvex program.", default=False) requires_grad: bool = Field( description=( "Allow gradient computation with respect to Parameters by calling problem.backward() " "or problem.derivative() after solving." ), default=False, ) enforce_dpp: bool = Field( description=( "Raise a DPPError for non-DPP problems when solving instead of only warning. " "Only relevant for problems involving Parameters." ), default=False, ) ignore_dpp: bool = Field( description=("Treat DPP problems as non-DPP, which may speed up compilation."), default=False, ) extra_options: dict[str, object] | None = Field( description="Additional keyword arguments forwarded directly to cvxpy Problem.solve().", default=None, ) ``` ### check_cvxpy_suitability ``` check_cvxpy_suitability(problem: Problem) -> bool ``` Checks whether a problem is suitable for being solved with CVXPY. Source code in `desdeo/tools/cvxpy_solver_interfaces.py` ``` def check_cvxpy_suitability(problem: Problem) -> bool: """Checks whether a problem is suitable for being solved with CVXPY.""" try: evaluator = CVXPYEvaluator(problem) for obj in problem.objectives: evaluator.set_optimization_target(obj.symbol) if not (evaluator.problem_model.is_dcp() or evaluator.problem_model.is_dgp()): return False break else: return True except Exception: return False ``` ### parse_cvxpy_optimizer_results ``` parse_cvxpy_optimizer_results( problem: Problem, evaluator: CVXPYEvaluator ) -> SolverResults ``` Parses results from CVXPYEvaluator's problem into DESDEO SolverResults. Parameters: | Name | Type | Description | Default | | ----------- | ---------------- | -------------------------------------------- | ---------- | | `problem` | `Problem` | the problem being solved. | *required* | | `evaluator` | `CVXPYEvaluator` | the evaluator utilized to solve the problem. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ---------------------- | | `SolverResults` | `SolverResults` | DESDEO solver results. | Source code in `desdeo/tools/cvxpy_solver_interfaces.py` ``` def parse_cvxpy_optimizer_results(problem: Problem, evaluator: CVXPYEvaluator) -> SolverResults: """Parses results from CVXPYEvaluator's problem into DESDEO SolverResults. Args: problem (Problem): the problem being solved. evaluator (CVXPYEvaluator): the evaluator utilized to solve the problem. Returns: SolverResults: DESDEO solver results. """ results = evaluator.get_values() variable_values = {var.symbol: results[var.symbol] for var in problem.variables} objective_values = {obj.symbol: results[obj.symbol] for obj in problem.objectives} constraint_values = ( {con.symbol: results[con.symbol] for con in problem.constraints} if problem.constraints is not None else None ) extra_func_values = ( {extra.symbol: results[extra.symbol] for extra in problem.extra_funcs} if problem.extra_funcs is not None else None ) scalarization_values = ( {scal.symbol: results[scal.symbol] for scal in problem.scalarization_funcs} if problem.scalarization_funcs is not None else None ) lagrange_multipliers = None success = evaluator.problem_model.status in {cp.OPTIMAL, cp.OPTIMAL_INACCURATE} if evaluator.problem_model.status == cp.OPTIMAL: status = "Optimal solution found." elif evaluator.problem_model.status == cp.OPTIMAL_INACCURATE: status = "Optimal solution found (inaccurate)." elif evaluator.problem_model.status == cp.INFEASIBLE: status = "Problem is infeasible." elif evaluator.problem_model.status == cp.UNBOUNDED: status = "Problem is unbounded." elif evaluator.problem_model.status == cp.INFEASIBLE_INACCURATE: status = "Problem is infeasible (inaccurate)." elif evaluator.problem_model.status == cp.UNBOUNDED_INACCURATE: status = "Problem is unbounded (inaccurate)." else: status = f"Optimization ended with status: {evaluator.problem_model.status}" msg = f"CVXPY solver status is: '{status}'" return SolverResults( optimal_variables=variable_values, optimal_objectives=objective_values, constraint_values=constraint_values, extra_func_values=extra_func_values, scalarization_values=scalarization_values, lagrange_multipliers=lagrange_multipliers, success=success, message=msg, ) ``` ## Nevergrad solver interfaces Solver interfaces to the optimization routines found in nevergrad. For more info, see https://facebookresearch.github.io/nevergrad/index.html ### \_default_nevergrad_generic_options ``` _default_nevergrad_generic_options = ( NevergradGenericOptions() ) ``` The set of default options for nevergrad's NgOpt optimizer. ### NevergradGenericOptions Bases: `BaseModel` Defines options to be passed to nevergrad's optimization routines. Source code in `desdeo/tools/ng_solver_interfaces.py` ``` class NevergradGenericOptions(BaseModel): """Defines options to be passed to nevergrad's optimization routines.""" budget: int = Field(description="The maximum number of allowed function evaluations.", default=100) """The maximum number of allowed function evaluations. Defaults to 100.""" num_workers: int = Field(description="The maximum number of allowed parallel evaluations.", default=1) """The maximum number of allowed parallel evaluations. This is currently used to define the batch size when evaluating problems. Defaults to 1.""" optimizer: Literal[*available_nevergrad_optimizers] = Field( description=( "The optimizer to be used. Must be one of `NGOpt`, `TwoPointDE`, `PortfolioDiscreteOnePlusOne`, " "`OnePlusOne`, `CMA`, `TBPSA`, `PSO`, `ScrHammersleySearchPlusMiddlePoint`, or `RandomSearch`. " "Defaults to `NGOpt`." ), default="NGOpt", ) """The optimizer to be used. Must be one of `NGOpt`, `TwoPointsDE`, `PortfolioDiscreteOnePlusOne`, `OnePlusOne`, `CMA`, `TBPSA`, `PSO`, `ScrHammersleySearchPlusMiddlePoint`, or `RandomSearch`. Defaults to `NGOpt`.""" seed: int | None = Field( description="An optional random seed for reproducible optimization. Defaults to None.", default=None ) """An optional random seed for reproducible optimization. If `None`, the optimizer's random state is left unseeded. Defaults to None.""" ``` #### budget ``` budget: int = Field( description="The maximum number of allowed function evaluations.", default=100, ) ``` The maximum number of allowed function evaluations. Defaults to 100. #### num_workers ``` num_workers: int = Field( description="The maximum number of allowed parallel evaluations.", default=1, ) ``` The maximum number of allowed parallel evaluations. This is currently used to define the batch size when evaluating problems. Defaults to 1. #### optimizer ``` optimizer: Literal[*available_nevergrad_optimizers,] = ( Field( description="The optimizer to be used. Must be one of `NGOpt`, `TwoPointDE`, `PortfolioDiscreteOnePlusOne`, `OnePlusOne`, `CMA`, `TBPSA`, `PSO`, `ScrHammersleySearchPlusMiddlePoint`, or `RandomSearch`. Defaults to `NGOpt`.", default="NGOpt", ) ) ``` The optimizer to be used. Must be one of `NGOpt`, `TwoPointsDE`, `PortfolioDiscreteOnePlusOne`, `OnePlusOne`, `CMA`, `TBPSA`, `PSO`, `ScrHammersleySearchPlusMiddlePoint`, or `RandomSearch`. Defaults to `NGOpt`. #### seed ``` seed: int | None = Field( description="An optional random seed for reproducible optimization. Defaults to None.", default=None, ) ``` An optional random seed for reproducible optimization. If `None`, the optimizer's random state is left unseeded. Defaults to None. ### NevergradGenericSolver Bases: `BaseSolver` Creates a solver that utilizes optimizations routines found in the nevergrad library. Source code in `desdeo/tools/ng_solver_interfaces.py` ``` class NevergradGenericSolver(BaseSolver): """Creates a solver that utilizes optimizations routines found in the nevergrad library.""" def __init__(self, problem: Problem, options: NevergradGenericOptions | None = _default_nevergrad_generic_options): """Creates a solver that utilizes optimizations routines found in the nevergrad library. These solvers are best utilized for black-box, gradient free optimization with computationally expensive function calls. Utilizing multiple workers is recommended (see `NevergradGenericOptions`) when function calls are heavily I/O bound. See https://facebookresearch.github.io/nevergrad/getting_started.html for further information on nevergrad and its solvers. References: Rapin, J., & Teytaud, O. (2018). Nevergrad - A gradient-free optimization platform. GitHub. https://GitHub.com/FacebookResearch/Nevergrad Args: problem (Problem): the problem to be solved. options (NgOptOptions | None): options to be passes to the solver. If none, `_default_ng_ngopt_options` are used. Defaults to None. """ self.problem = problem self.options = options if options is not None else _default_nevergrad_generic_options self.evaluator = SympyEvaluator(problem) def solve(self, target: str) -> SolverResults: """Solve the problem for the given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: the results of the optimization. """ def _make_scalar(var): if var.initial_value is not None: init = var.initial_value elif var.lowerbound is not None and var.upperbound is not None: init = (var.lowerbound + var.upperbound) / 2 elif var.lowerbound is not None: init = var.lowerbound elif var.upperbound is not None: init = var.upperbound else: init = 0.0 scalar = ng.p.Scalar(init=init) if var.lowerbound is not None or var.upperbound is not None: scalar.set_bounds(var.lowerbound, var.upperbound) return scalar parametrization = ng.p.Dict(**{var.symbol: _make_scalar(var) for var in self.problem.variables}) # When a seed is given, make the run reproducible. nevergrad (and NGOpt's optimizer selection) # draws from numpy's global RNG as well as the parametrization's own random state, so the global # RNG must be seeded before anything is constructed. It is restored in the `finally` below so the # caller's global numpy state is not mutated. rng_state = None if self.options.seed is not None: rng_state = np.random.get_state() # noqa: NPY002 np.random.seed(self.options.seed) # noqa: NPY002 optimizer = ng.optimizers.registry[self.options.optimizer]( parametrization=parametrization, **self.options.model_dump(exclude={"optimizer", "seed"}) ) if self.options.seed is not None: optimizer.parametrization.random_state.seed(self.options.seed) constraint_symbols = ( None if self.problem.constraints is None else [con.symbol for con in self.problem.constraints] ) try: if optimizer.num_workers == 1: # single thread recommendation = optimizer.minimize( lambda xs, t=target: self.evaluator.evaluate_target(xs, t), constraint_violation=[ lambda xs, t=con_t: self.evaluator.evaluate_target(xs, t) for con_t in constraint_symbols ] if constraint_symbols is not None else None, ) elif optimizer.num_workers > 1: # multiple processors with ThreadPoolExecutor(max_workers=optimizer.num_workers) as executor: recommendation = optimizer.minimize( lambda xs, t=target: self.evaluator.evaluate_target(xs, t), constraint_violation=[ lambda xs, t=con_t: self.evaluator.evaluate_target(xs, t) for con_t in constraint_symbols ] if constraint_symbols is not None else None, executor=executor, batch_mode=False, ) msg = f"Recommendation found by {self.options.optimizer}." success = True except Exception as e: msg = f"{self.options.optimizer} failed. Possible reason: {e}" success = False finally: if rng_state is not None: np.random.set_state(rng_state) # noqa: NPY002 result = {"recommendation": recommendation, "message": msg, "success": success} return parse_ng_results(result, self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: NevergradGenericOptions | None = _default_nevergrad_generic_options, ) ``` Creates a solver that utilizes optimizations routines found in the nevergrad library. These solvers are best utilized for black-box, gradient free optimization with computationally expensive function calls. Utilizing multiple workers is recommended (see `NevergradGenericOptions`) when function calls are heavily I/O bound. See https://facebookresearch.github.io/nevergrad/getting_started.html for further information on nevergrad and its solvers. References Rapin, J., & Teytaud, O. (2018). Nevergrad - A gradient-free optimization platform. GitHub. https://GitHub.com/FacebookResearch/Nevergrad Parameters: | Name | Type | Description | Default | | --------- | -------------- | ------------------------- | --------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the problem to be solved. | *required* | | `options` | \`NgOptOptions | None\` | options to be passes to the solver. If none, \_default_ng_ngopt_options are used. Defaults to None. | Source code in `desdeo/tools/ng_solver_interfaces.py` ``` def __init__(self, problem: Problem, options: NevergradGenericOptions | None = _default_nevergrad_generic_options): """Creates a solver that utilizes optimizations routines found in the nevergrad library. These solvers are best utilized for black-box, gradient free optimization with computationally expensive function calls. Utilizing multiple workers is recommended (see `NevergradGenericOptions`) when function calls are heavily I/O bound. See https://facebookresearch.github.io/nevergrad/getting_started.html for further information on nevergrad and its solvers. References: Rapin, J., & Teytaud, O. (2018). Nevergrad - A gradient-free optimization platform. GitHub. https://GitHub.com/FacebookResearch/Nevergrad Args: problem (Problem): the problem to be solved. options (NgOptOptions | None): options to be passes to the solver. If none, `_default_ng_ngopt_options` are used. Defaults to None. """ self.problem = problem self.options = options if options is not None else _default_nevergrad_generic_options self.evaluator = SympyEvaluator(problem) ``` #### solve ``` solve(target: str) -> SolverResults ``` Solve the problem for the given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | the symbol of the objective function to be optimized. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | -------------------------------- | | `SolverResults` | `SolverResults` | the results of the optimization. | Source code in `desdeo/tools/ng_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solve the problem for the given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: the results of the optimization. """ def _make_scalar(var): if var.initial_value is not None: init = var.initial_value elif var.lowerbound is not None and var.upperbound is not None: init = (var.lowerbound + var.upperbound) / 2 elif var.lowerbound is not None: init = var.lowerbound elif var.upperbound is not None: init = var.upperbound else: init = 0.0 scalar = ng.p.Scalar(init=init) if var.lowerbound is not None or var.upperbound is not None: scalar.set_bounds(var.lowerbound, var.upperbound) return scalar parametrization = ng.p.Dict(**{var.symbol: _make_scalar(var) for var in self.problem.variables}) # When a seed is given, make the run reproducible. nevergrad (and NGOpt's optimizer selection) # draws from numpy's global RNG as well as the parametrization's own random state, so the global # RNG must be seeded before anything is constructed. It is restored in the `finally` below so the # caller's global numpy state is not mutated. rng_state = None if self.options.seed is not None: rng_state = np.random.get_state() # noqa: NPY002 np.random.seed(self.options.seed) # noqa: NPY002 optimizer = ng.optimizers.registry[self.options.optimizer]( parametrization=parametrization, **self.options.model_dump(exclude={"optimizer", "seed"}) ) if self.options.seed is not None: optimizer.parametrization.random_state.seed(self.options.seed) constraint_symbols = ( None if self.problem.constraints is None else [con.symbol for con in self.problem.constraints] ) try: if optimizer.num_workers == 1: # single thread recommendation = optimizer.minimize( lambda xs, t=target: self.evaluator.evaluate_target(xs, t), constraint_violation=[ lambda xs, t=con_t: self.evaluator.evaluate_target(xs, t) for con_t in constraint_symbols ] if constraint_symbols is not None else None, ) elif optimizer.num_workers > 1: # multiple processors with ThreadPoolExecutor(max_workers=optimizer.num_workers) as executor: recommendation = optimizer.minimize( lambda xs, t=target: self.evaluator.evaluate_target(xs, t), constraint_violation=[ lambda xs, t=con_t: self.evaluator.evaluate_target(xs, t) for con_t in constraint_symbols ] if constraint_symbols is not None else None, executor=executor, batch_mode=False, ) msg = f"Recommendation found by {self.options.optimizer}." success = True except Exception as e: msg = f"{self.options.optimizer} failed. Possible reason: {e}" success = False finally: if rng_state is not None: np.random.set_state(rng_state) # noqa: NPY002 result = {"recommendation": recommendation, "message": msg, "success": success} return parse_ng_results(result, self.problem, self.evaluator) ``` ### parse_ng_results ``` parse_ng_results( results: dict, problem: Problem, evaluator: SympyEvaluator, ) -> SolverResults ``` Parses the optimization results returned by nevergrad solvers. Parameters: | Name | Type | Description | Default | | ----------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `results` | `dict` | the results. A dict with at least the keys recommendation, which points to a parametrization returned by nevergrad solvers, message with information about the optimization, and success indicating whther a recommendation was found successfully or not. | *required* | | `problem` | `Problem` | the problem the results belong to. | *required* | | `evaluator` | `GenericEvaluator` | the evaluator used to evaluate the problem. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ----------------------------------------------------------- | | `SolverResults` | `SolverResults` | a pydantic dataclass withthe relevant optimization results. | Source code in `desdeo/tools/ng_solver_interfaces.py` ``` def parse_ng_results(results: dict, problem: Problem, evaluator: SympyEvaluator) -> SolverResults: """Parses the optimization results returned by nevergrad solvers. Args: results (dict): the results. A dict with at least the keys `recommendation`, which points to a parametrization returned by nevergrad solvers, `message` with information about the optimization, and `success` indicating whther a recommendation was found successfully or not. problem (Problem): the problem the results belong to. evaluator (GenericEvaluator): the evaluator used to evaluate the problem. Returns: SolverResults: a pydantic dataclass withthe relevant optimization results. """ optimal_variables = results["recommendation"].value success = results["success"] msg = results["message"] results = evaluator.evaluate(optimal_variables) optimal_objectives = {obj.symbol: results[obj.symbol] for obj in problem.objectives} constraint_values = ( {con.symbol: results[con.symbol] for con in problem.constraints} if problem.constraints is not None else None ) extra_func_values = ( {extra.symbol: results[extra.symbol] for extra in problem.extra_funcs} if problem.extra_funcs is not None else None ) scalarization_values = ( {scal.symbol: results[scal.symbol] for scal in problem.scalarization_funcs} if problem.scalarization_funcs is not None else None ) return SolverResults( optimal_variables=optimal_variables, optimal_objectives=optimal_objectives, constraint_values=constraint_values, extra_func_values=extra_func_values, scalarization_values=scalarization_values, success=success, message=msg, ) ``` ## Scipy solver interfaces Solver interfaces to the optimization routines found in scipy. These solvers can solve various scalarized problems of multiobjective optimization problems. ### EvalTargetEnum Bases: `StrEnum` An enum that describe whether the evaluator target is an objective or a constraint. Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` class EvalTargetEnum(StrEnum): """An enum that describe whether the evaluator target is an objective or a constraint.""" objective = "objective" constraint = "constraint" ``` ### ScipyDeOptions Bases: `BaseModel` Defines a pydantic model to store and pass options to the Scipy differential evolution solver. Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` class ScipyDeOptions(BaseModel): """Defines a pydantic model to store and pass options to the Scipy differential evolution solver.""" initial_guess: dict[str, float | None] | None = Field( description="The initial guess to be utilized in the solver. For variables with a None as their initial " "guess, the mid-point of the variable's lower and upper bound is utilized as the initial" "guess. If None, it is assumed that there are no initial guesses for any of the variables.", default=None, ) de_kwargs: dict | None = Field( description="Custom keyword arguments to be forwarded to `scipy.optimize.differential_evolution`.", default=None ) ``` ### ScipyDeSolver Bases: `BaseSolver` Creates a scipy solver that utilizes differential evolution. Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` class ScipyDeSolver(BaseSolver): """Creates a scipy solver that utilizes differential evolution.""" def __init__( self, problem: Problem, options: ScipyDeOptions | None = _default_scipy_de_options, ): """Creates a solver that utilizes the `scipy.optimize.differential_evolution` routine. The `scipy.optimize.differential_evolution` routine is fully accessible through this function. For additional details and explanation of some of the argumetns, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.differential_evolution.html Args: problem (Problem): the multiobjective optimization problem to be solved. options (ScipyDeOptions | None): Pydantic model containing arguments used by scipy DE solver. If `None` is passed, defaults to `_default_scipy_de_options` defined in this source file. """ if options is None: options = _default_scipy_de_options initial_guess = options.initial_guess de_kwargs = options.de_kwargs if variable_dimension_enumerate(problem) not in SUPPORTED_VAR_DIMENSIONS: msg = "ScipyDeSolver only supports scalar variables." raise SolverError(msg) self.problem = problem if de_kwargs is None: de_kwargs = { "strategy": "best1bin", "maxiter": 1000, "popsize": 15, "tol": 0.01, "mutation": (0.5, 1), "recombination": 0.7, "seed": None, "callback": None, "disp": False, "polish": True, "init": "latinhypercube", "atol": 0, "updating": "deferred", "workers": 1, "integrality": None, "vectorized": True, # the constraints for scipy_de need to be fixed first for this to work } self.de_kwargs = de_kwargs # variable bounds self.bounds = get_variable_bounds_pairs(problem) # initial guess. If no guess is present for a variable, said variable's mid point of its # lower abd upper bound is used instead if initial_guess is None: self.initial_guess = set_initial_guess(problem) else: self.initial_guess = initial_guess self.evaluator = PolarsEvaluator(problem) self.constraints = ( create_scipy_object_constraints(self.problem, self.evaluator) if self.problem.constraints is not None else () ) def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: results of the optimization. """ # If the target is an objective symbol, use its _min form objective_symbols = {obj.symbol for obj in self.problem.objectives} eval_target = f"{target}_min" if target in objective_symbols else target optimization_result: _ScipyOptimizeResult = _scipy_de( get_scipy_eval(self.problem, self.evaluator, eval_target, EvalTargetEnum.objective), bounds=self.bounds, x0=self.initial_guess, constraints=self.constraints, **self.de_kwargs, ) # parse the results return parse_scipy_optimization_result(optimization_result, self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: ScipyDeOptions | None = _default_scipy_de_options, ) ``` Creates a solver that utilizes the `scipy.optimize.differential_evolution` routine. The `scipy.optimize.differential_evolution` routine is fully accessible through this function. For additional details and explanation of some of the argumetns, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.differential_evolution.html Parameters: | Name | Type | Description | Default | | --------- | ---------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `problem` | `Problem` | the multiobjective optimization problem to be solved. | *required* | | `options` | \`ScipyDeOptions | None\` | Pydantic model containing arguments used by scipy DE solver. If None is passed, defaults to \_default_scipy_de_options defined in this source file. | Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def __init__( self, problem: Problem, options: ScipyDeOptions | None = _default_scipy_de_options, ): """Creates a solver that utilizes the `scipy.optimize.differential_evolution` routine. The `scipy.optimize.differential_evolution` routine is fully accessible through this function. For additional details and explanation of some of the argumetns, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.differential_evolution.html Args: problem (Problem): the multiobjective optimization problem to be solved. options (ScipyDeOptions | None): Pydantic model containing arguments used by scipy DE solver. If `None` is passed, defaults to `_default_scipy_de_options` defined in this source file. """ if options is None: options = _default_scipy_de_options initial_guess = options.initial_guess de_kwargs = options.de_kwargs if variable_dimension_enumerate(problem) not in SUPPORTED_VAR_DIMENSIONS: msg = "ScipyDeSolver only supports scalar variables." raise SolverError(msg) self.problem = problem if de_kwargs is None: de_kwargs = { "strategy": "best1bin", "maxiter": 1000, "popsize": 15, "tol": 0.01, "mutation": (0.5, 1), "recombination": 0.7, "seed": None, "callback": None, "disp": False, "polish": True, "init": "latinhypercube", "atol": 0, "updating": "deferred", "workers": 1, "integrality": None, "vectorized": True, # the constraints for scipy_de need to be fixed first for this to work } self.de_kwargs = de_kwargs # variable bounds self.bounds = get_variable_bounds_pairs(problem) # initial guess. If no guess is present for a variable, said variable's mid point of its # lower abd upper bound is used instead if initial_guess is None: self.initial_guess = set_initial_guess(problem) else: self.initial_guess = initial_guess self.evaluator = PolarsEvaluator(problem) self.constraints = ( create_scipy_object_constraints(self.problem, self.evaluator) if self.problem.constraints is not None else () ) ``` #### solve ``` solve(target: str) -> SolverResults ``` Solve the problem for a given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | the symbol of the objective function to be optimized. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ---------------------------- | | `SolverResults` | `SolverResults` | results of the optimization. | Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: results of the optimization. """ # If the target is an objective symbol, use its _min form objective_symbols = {obj.symbol for obj in self.problem.objectives} eval_target = f"{target}_min" if target in objective_symbols else target optimization_result: _ScipyOptimizeResult = _scipy_de( get_scipy_eval(self.problem, self.evaluator, eval_target, EvalTargetEnum.objective), bounds=self.bounds, x0=self.initial_guess, constraints=self.constraints, **self.de_kwargs, ) # parse the results return parse_scipy_optimization_result(optimization_result, self.problem, self.evaluator) ``` ### ScipyMinimizeOptions Bases: `BaseModel` Defines a pydantic model to store and pass options to the Scipy Minimize solver. Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` class ScipyMinimizeOptions(BaseModel): """Defines a pydantic model to store and pass options to the Scipy Minimize solver.""" initial_guess: dict[str, float | None] | None = Field( description="The initial guess to be utilized in the solver. For variables with a None as their" "initial guess, the mid-point of the variable's lower and upper bound is utilized as the " "initial guess. If None, it is assumed that there are no initial guesses for any of the variables.", default=None, ) method: str | None = Field( description="The scipy.optimize.minimize method to beused. If None, a method is selected " "automatically based on the properties of the objective (does it have constraints?).", default=None, ) method_kwargs: dict | None = Field( description="The keyword arguments passed to the scipy.optimize.minimize method.", default=None ) tol: float | None = Field(description="Tolerance for termination.", default=None) additional_options: dict | None = Field(description="Additional solver options.", default=None) ``` ### ScipyMinimizeSolver Bases: `BaseSolver` Creates a scipy solver that utilizes the `minimization` routine. Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` class ScipyMinimizeSolver(BaseSolver): """Creates a scipy solver that utilizes the `minimization` routine.""" def __init__(self, problem: Problem, options: ScipyMinimizeOptions | None = _default_scipy_minimize_options): """Initializes a solver that utilizes the `scipy.optimize.minimize` routine. The `scipy.optimize.minimze` routine is fully accessible through this function. For additional details and explanation of some of the argumetns, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize Args: problem (Problem): the multiobjective optimization problem to be solved. options: (ScipyMinimizeOptions | None): Pydantic model containing args for scipy minimize solver. If `None` is passed, defaults to `_default_scipy_minimize_options` defined in this source file. """ if variable_dimension_enumerate(problem) not in SUPPORTED_VAR_DIMENSIONS: msg = "ScipyMinimizeSolver only supports scalar variables." raise SolverError(msg) if options is None: options = _default_scipy_minimize_options initial_guess = options.initial_guess self.problem = problem self.method = options.method self.method_kwargs = options.method_kwargs self.tol = options.tol self.additional_options = options.additional_options # variables bounds as (min, max pairs) self.bounds = get_variable_bounds_pairs(problem) # the initial guess as a simple sequence. If no initial value is set for some variable, # then the initial value defaults to middle of the upper and lower bounds. if initial_guess is not None: self.initial_guess = [initial_guess[var.symbol] for var in self.problem.variables] else: self.initial_guess = set_initial_guess(problem) self.evaluator = PolarsEvaluator(problem) self.constraints = ( create_scipy_dict_constraints(self.problem, self.evaluator) if self.problem.constraints is not None else None ) def solve(self, target: str) -> SolverResults: """Solves the problem for a given target. Args: target (str): the sumbol of the objective function to be optimized. Returns: SolverResults: results of the optimization. """ # If the target is an objective symbol, use its _min form objective_symbols = {obj.symbol for obj in self.problem.objectives} eval_target = f"{target}_min" if target in objective_symbols else target optimization_result: _ScipyOptimizeResult = _scipy_minimize( get_scipy_eval(self.problem, self.evaluator, eval_target, EvalTargetEnum.objective), self.initial_guess, method=self.method, bounds=self.bounds, constraints=self.constraints, options=self.additional_options, tol=self.tol, ) # pare and return the results return parse_scipy_optimization_result(optimization_result, self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: ScipyMinimizeOptions | None = _default_scipy_minimize_options, ) ``` Initializes a solver that utilizes the `scipy.optimize.minimize` routine. The `scipy.optimize.minimze` routine is fully accessible through this function. For additional details and explanation of some of the argumetns, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize Parameters: | Name | Type | Description | Default | | --------- | ---------------------- | ----------------------------------------------------- | --------------------- | | `problem` | `Problem` | the multiobjective optimization problem to be solved. | *required* | | `options` | \`ScipyMinimizeOptions | None\` | (ScipyMinimizeOptions | Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def __init__(self, problem: Problem, options: ScipyMinimizeOptions | None = _default_scipy_minimize_options): """Initializes a solver that utilizes the `scipy.optimize.minimize` routine. The `scipy.optimize.minimze` routine is fully accessible through this function. For additional details and explanation of some of the argumetns, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize Args: problem (Problem): the multiobjective optimization problem to be solved. options: (ScipyMinimizeOptions | None): Pydantic model containing args for scipy minimize solver. If `None` is passed, defaults to `_default_scipy_minimize_options` defined in this source file. """ if variable_dimension_enumerate(problem) not in SUPPORTED_VAR_DIMENSIONS: msg = "ScipyMinimizeSolver only supports scalar variables." raise SolverError(msg) if options is None: options = _default_scipy_minimize_options initial_guess = options.initial_guess self.problem = problem self.method = options.method self.method_kwargs = options.method_kwargs self.tol = options.tol self.additional_options = options.additional_options # variables bounds as (min, max pairs) self.bounds = get_variable_bounds_pairs(problem) # the initial guess as a simple sequence. If no initial value is set for some variable, # then the initial value defaults to middle of the upper and lower bounds. if initial_guess is not None: self.initial_guess = [initial_guess[var.symbol] for var in self.problem.variables] else: self.initial_guess = set_initial_guess(problem) self.evaluator = PolarsEvaluator(problem) self.constraints = ( create_scipy_dict_constraints(self.problem, self.evaluator) if self.problem.constraints is not None else None ) ``` #### solve ``` solve(target: str) -> SolverResults ``` Solves the problem for a given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | the sumbol of the objective function to be optimized. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ---------------------------- | | `SolverResults` | `SolverResults` | results of the optimization. | Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solves the problem for a given target. Args: target (str): the sumbol of the objective function to be optimized. Returns: SolverResults: results of the optimization. """ # If the target is an objective symbol, use its _min form objective_symbols = {obj.symbol for obj in self.problem.objectives} eval_target = f"{target}_min" if target in objective_symbols else target optimization_result: _ScipyOptimizeResult = _scipy_minimize( get_scipy_eval(self.problem, self.evaluator, eval_target, EvalTargetEnum.objective), self.initial_guess, method=self.method, bounds=self.bounds, constraints=self.constraints, options=self.additional_options, tol=self.tol, ) # pare and return the results return parse_scipy_optimization_result(optimization_result, self.problem, self.evaluator) ``` ### create_scipy_dict_constraints ``` create_scipy_dict_constraints( problem: Problem, evaluator: PolarsEvaluator ) -> dict ``` Creates a dict with scipy compatible constraints. It is assumed that there are constraints defined in problem. Parameters: | Name | Type | Description | Default | | ----------- | ------------------ | ------------------------------------------- | ---------- | | `problem` | `Problem` | the Problem with the constraints. | *required* | | `evaluator` | `GenericEvaluator` | the evaluator utilized to evaluate problem. | *required* | Returns: | Name | Type | Description | | ------ | ------ | ----------------------------------------- | | `dict` | `dict` | a dict with scipy compatible constraints. | Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def create_scipy_dict_constraints(problem: Problem, evaluator: PolarsEvaluator) -> dict: """Creates a dict with scipy compatible constraints. It is assumed that there are constraints defined in problem. Args: problem (Problem): the Problem with the constraints. evaluator (GenericEvaluator): the evaluator utilized to evaluate problem. Returns: dict: a dict with scipy compatible constraints. """ return [ { "type": "ineq" if constraint.cons_type == ConstraintTypeEnum.LTE else "eq", "fun": get_scipy_eval(problem, evaluator, constraint.symbol, eval_target=EvalTargetEnum.constraint), } for constraint in problem.constraints ] ``` ### create_scipy_object_constraints ``` create_scipy_object_constraints( problem: Problem, evaluator: PolarsEvaluator ) -> list[NonlinearConstraint] ``` Creates a list with scipy constraint object `NonLinearConstraints` used by some scipy routines. For more infor, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.NonlinearConstraint.html#scipy-optimize-nonlinearconstraint Parameters: | Name | Type | Description | Default | | ----------- | ------------------ | -------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem with the original constraint to be utilized in creating the list of constraints. | *required* | | `evaluator` | `GenericEvaluator` | the evaluator corresponding to problem that can be used to evaluate the constraints. | *required* | Returns: | Type | Description | | --------------------------- | --------------------------------------------------------------------------- | | `list[NonlinearConstraint]` | list\[NonlinearConstraint\]: a list of scipy's NonLinearConstraint objects. | Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def create_scipy_object_constraints(problem: Problem, evaluator: PolarsEvaluator) -> list[NonlinearConstraint]: """Creates a list with scipy constraint object `NonLinearConstraints` used by some scipy routines. For more infor, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.NonlinearConstraint.html#scipy-optimize-nonlinearconstraint Args: problem (Problem): the problem with the original constraint to be utilized in creating the list of constraints. evaluator (GenericEvaluator): the evaluator corresponding to problem that can be used to evaluate the constraints. Returns: list[NonlinearConstraint]: a list of scipy's NonLinearConstraint objects. """ return NonlinearConstraint( fun=get_scipy_eval(problem, evaluator, "", eval_target=EvalTargetEnum.constraint), lb=0, # constraint value must be between 0 and inf, e.g., positive. ub=float("inf"), # since in scipy, a constraint is respected when its value is positive. See scipy_eval. ) ``` ### get_scipy_eval ``` get_scipy_eval( problem: Problem, evaluator: PolarsEvaluator, target: str, eval_target: EvalTargetEnum, ) -> Callable[[list[float | int]], list[float | int]] ``` Wraps the problem and evaluator into a callable function that can be used by scipy routines. The returned function expects an array-like argument, such as a numpy array or list. Parameters: | Name | Type | Description | Default | | ------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | | `problem` | `Problem` | the problem being solved. | *required* | | `evaluator` | `GenericEvaluator` | the evaluator to evaluate the problem being solved. | *required* | | `target` | `str` | the symbol of the objective to of the optimization, defined in problem. | *required* | | `eval_target` | `EvalTargetEnum` | either objective or constraints. If objective, it is assumed that the evalution is about evaluating the objective function of the single-objective optimization problem being solved, e.g., a scalarization function defined in problem. If constraint, then the evalution is assumed to be about evaluating the constraints defined in problem. | *required* | Returns: | Type | Description | | ------------------------- | -------------------- | | \`Callable\[\[list\[float | int\]\], list\[float | Note Constraints in scipy are defined such that a positive number means the constraint is respected. In DESDEO, this is the opposite, e.g., a positive number means a constraint is breached. We take this into account when returning the constraint values, but this does not affect the constraint values computed for the true constraints. Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def get_scipy_eval( problem: Problem, evaluator: PolarsEvaluator, target: str, eval_target: EvalTargetEnum, ) -> Callable[[list[float | int]], list[float | int]]: """Wraps the problem and evaluator into a callable function that can be used by scipy routines. The returned function expects an array-like argument, such as a numpy array or list. Args: problem (Problem): the problem being solved. evaluator (GenericEvaluator): the evaluator to evaluate the problem being solved. target (str): the symbol of the objective to of the optimization, defined in problem. eval_target (EvalTargetEnum): either objective or constraints. If objective, it is assumed that the evalution is about evaluating the objective function of the single-objective optimization problem being solved, e.g., a scalarization function defined in problem. If constraint, then the evalution is assumed to be about evaluating the constraints defined in problem. Returns: Callable[[list[float | int]], list[float | int]]: a function that takes as its argument an array like object. Note: Constraints in scipy are defined such that a positive number means the constraint is respected. In DESDEO, this is the opposite, e.g., a positive number means a constraint is breached. We take this into account when returning the constraint values, but this does not affect the constraint values computed for the true constraints. """ def scipy_eval(x: list[float | int]) -> list[float | int]: """An evaluator to be used in scipy routines. Args: x (list[float | int]): an array like, such as a numpy array or list.append Raises: SolverError: when an invalid evaluator target is specified. Returns: list[float | int]: an array like. """ # TODO: Consider caching the results of evaluator.evaluate evalutor_args = { problem.variables[i].symbol: [x[i]] if isinstance(x[i], float | int) else x[i] for i in range(len(problem.variables)) } if eval_target == EvalTargetEnum.objective: evaluator_res = evaluator.evaluate(evalutor_args) # evaluata objective (scalarized) return evaluator_res.to_dict(as_series=False)[target] if eval_target == EvalTargetEnum.constraint: evaluator_df = evaluator.evaluate(evalutor_args) # evaluate constraint # put the minus here because scipy expect positive constraints values when the constraint # is respected. But in DESDEO, we define constraints s.t., a negative value means the constraint # is recpected, therefore, it needs to be flipped here. con_symbols = [constraint.symbol for constraint in problem.constraints] res_dict = evaluator_df[con_symbols].to_dict(as_series=False) res = np.array([np.array(res_dict[symbol]) for symbol in con_symbols]) # squeeze important for minimization routines return -np.squeeze(res, axis=-1) if res.shape[-1] == 1 else -res # non-existing eval_target msg = f"'eval_target' = '{eval_target} not supported. Must be one of {list(EvalTargetEnum)}." raise SolverError(msg) return scipy_eval ``` ### get_variable_bounds_pairs ``` get_variable_bounds_pairs( problem: Problem, ) -> list[tuple[float | int, float | int]] ``` Returns the variable bounds defined in a Problem as a list of tuples. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------------------------- | ---------- | | `problem` | `Problem` | the problem with the variables of interest. | *required* | Returns: | Type | Description | | -------------------- | ----------- | | \`list\[tuple\[float | int, float | Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def get_variable_bounds_pairs(problem: Problem) -> list[tuple[float | int, float | int]]: """Returns the variable bounds defined in a Problem as a list of tuples. Args: problem (Problem): the problem with the variables of interest. Returns: list[tuple[float | int, float | int]]: a list of tuples, the first element of each tuple is the lower bound of a variable and the second its upper bound. Each tuple corresponds to a variable. """ return [(variable.lowerbound, variable.upperbound) for variable in problem.variables] ``` ### parse_scipy_optimization_result ``` parse_scipy_optimization_result( optimization_result: OptimizeResult, problem: Problem, evaluator: PolarsEvaluator, ) -> SolverResults ``` Parses the optimization results returned by various scipy methods. For documentation, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.OptimizeResult.html#scipy.optimize.OptimizeResult Parameters: | Name | Type | Description | Default | | --------------------- | ------------------ | ----------------------------------------------------------------------- | ---------- | | `optimization_result` | `OptimizeResult` | the optimization results. | *required* | | `problem` | `Problem` | the problem to which the optimization results correspond to. | *required* | | `evaluator` | `GenericEvaluator` | the evaluator that has been used in computing the optimization results. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ------------------------------------------------------------ | | `SolverResults` | `SolverResults` | a pydantic dataclass with the relevant optimization results. | Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def parse_scipy_optimization_result( optimization_result: _ScipyOptimizeResult, problem: Problem, evaluator: PolarsEvaluator ) -> SolverResults: """Parses the optimization results returned by various scipy methods. For documentation, see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.OptimizeResult.html#scipy.optimize.OptimizeResult Args: optimization_result (_ScipyOptimizeResult): the optimization results. problem (Problem): the problem to which the optimization results correspond to. evaluator (GenericEvaluator): the evaluator that has been used in computing the optimization results. Returns: SolverResults: a pydantic dataclass with the relevant optimization results. """ x_opt = optimization_result.x success_opt = optimization_result.success msg_opt = optimization_result.message results = evaluator.evaluate({problem.variables[i].symbol: [x_opt[i]] for i in range(len(problem.variables))}) optimal_objectives = {obj.symbol: results[obj.symbol][0] for obj in problem.objectives} constraint_values = ( {con.symbol: results[con.symbol][0] for con in problem.constraints} if problem.constraints is not None else None ) """ objective_symbols = [obj.symbol for obj in problem.objectives] f_res = results[objective_symbols] optimal_objectives = {symbol: f_res[symbol][0] for symbol in objective_symbols} if problem.constraints is not None: const_symbols = [const.symbol for const in problem.constraints] const_res = results[const_symbols] constraint_values = {symbol: const_res[symbol][0] for symbol in const_symbols} else: constraint_values = None """ extra_func_values = ( {extra.symbol: results[extra.symbol][0] for extra in problem.extra_funcs} if problem.extra_funcs is not None else None ) scalarization_values = ( {scal.symbol: results[scal.symbol][0] for scal in problem.scalarization_funcs} if problem.scalarization_funcs is not None else None ) return SolverResults( optimal_variables={problem.variables[i].symbol: x_opt[i] for i in range(len(problem.variables))}, optimal_objectives=optimal_objectives, constraint_values=constraint_values, extra_func_values=extra_func_values, scalarization_values=scalarization_values, success=success_opt, message=msg_opt, ) ``` ### set_initial_guess ``` set_initial_guess(problem: Problem) -> list[float | int] ``` Sets or gets the initial guess for each variable defined in a Problem. For variables without an initial guess, the initial guess is set to the middle point of the variable's lower and upper bound. If only one of the bounds is defined, that bound is used instead. If neither bound is defined, the initial guess defaults to 0. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem with the variables of which the initial values are of interest. | *required* | Returns: | Type | Description | | ------------- | ----------- | | \`list\[float | int\]\` | Source code in `desdeo/tools/scipy_solver_interfaces.py` ``` def set_initial_guess(problem: Problem) -> list[float | int]: """Sets or gets the initial guess for each variable defined in a Problem. For variables without an initial guess, the initial guess is set to the middle point of the variable's lower and upper bound. If only one of the bounds is defined, that bound is used instead. If neither bound is defined, the initial guess defaults to 0. Args: problem (Problem): the problem with the variables of which the initial values are of interest. Returns: list[float | int]: a list of numbers, each number represents the initial guess of each variable in the problem. """ guesses = [] for variable in problem.variables: if variable.initial_value is not None: guesses.append(variable.initial_value) elif variable.lowerbound is not None and variable.upperbound is not None: guesses.append((variable.upperbound - variable.lowerbound) / 2 + variable.lowerbound) elif variable.lowerbound is not None: guesses.append(variable.lowerbound) elif variable.upperbound is not None: guesses.append(variable.upperbound) else: guesses.append(0) return guesses ``` ## Pyomo solver interfaces Defines solver interfaces for pyomo. ### \_default_bonmin_options ``` _default_bonmin_options = BonminOptions() ``` Defines Bonmin options with default values. ### \_default_cbc_options ``` _default_cbc_options = CbcOptions() ``` Defines CBC options with default values. ### \_default_ipopt_options ``` _default_ipopt_options = IpoptOptions() ``` Defines Ipopt optins with default values. ### BonminOptions Bases: `BaseModel` Defines a pydantic model to store and pass options to the Bonmin solver. Because Bonmin utilizes many sub-solver, the options specific to Bonmin must be prefixed in their name with 'bonmin.{option_name}', e.g., `bonmin.integer_tolerance`. For a list of options, see https://www.coin-or.org/Bonmin/options_list.html Note Not all options are available through this model. Please add options as they are needed and make a pull request. Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` class BonminOptions(BaseModel): """Defines a pydantic model to store and pass options to the Bonmin solver. Because Bonmin utilizes many sub-solver, the options specific to Bonmin must be prefixed in their name with 'bonmin.{option_name}', e.g., `bonmin.integer_tolerance`. For a list of options, see https://www.coin-or.org/Bonmin/options_list.html Note: Not all options are available through this model. Please add options as they are needed and make a pull request. """ tol: float = Field(description="Sets the convergence tolerance of ipopt. Defaults to 1e-8.", default=1e-8) """Sets the convergence tolerance of ipopt. Defaults to 1e-8.""" bonmin_integer_tolerance: float = Field( description="Numbers within this value of an integer are considered integers. Defaults to 1e-6.", default=1e-6 ) """Numbers within this value of an integer are considered integers. Defaults to 1e-6.""" bonmin_algorithm: str = Field( description=( "Presets some of the options in Bonmin based on the algorithm choice. Defaults to 'B-BB'. " "A good first option to try is 'B-Hyb'." ), default="B-BB", ) """Presets some of the options in Bonmin based on the algorithm choice. Defaults to 'B-BB'. A good first option to try is 'B-Hyb'. """ def asdict(self) -> dict[str, float]: """Converts the Pydantic model into a dict so that Bonmin specific options are in the correct format. This means that the attributes starting with `bonmin_optionname` will be converted to keys in the format `bonmin.optionname` in the returned dict. """ output = {} for field_name, _ in BonminOptions.model_fields.items(): if (rest := field_name.split(sep="_"))[0] == "bonmin": # Convert to Bonmin specific format output[f"bonmin.{'_'.join(rest[1:])}"] = getattr(self, field_name) else: # Keep the field as is output[field_name] = getattr(self, field_name) return output ``` #### bonmin_algorithm ``` bonmin_algorithm: str = Field( description="Presets some of the options in Bonmin based on the algorithm choice. Defaults to 'B-BB'. A good first option to try is 'B-Hyb'.", default="B-BB", ) ``` Presets some of the options in Bonmin based on the algorithm choice. Defaults to 'B-BB'. A good first option to try is 'B-Hyb'. #### bonmin_integer_tolerance ``` bonmin_integer_tolerance: float = Field( description="Numbers within this value of an integer are considered integers. Defaults to 1e-6.", default=1e-06, ) ``` Numbers within this value of an integer are considered integers. Defaults to 1e-6. #### tol ``` tol: float = Field( description="Sets the convergence tolerance of ipopt. Defaults to 1e-8.", default=1e-08, ) ``` Sets the convergence tolerance of ipopt. Defaults to 1e-8. #### asdict ``` asdict() -> dict[str, float] ``` Converts the Pydantic model into a dict so that Bonmin specific options are in the correct format. This means that the attributes starting with `bonmin_optionname` will be converted to keys in the format `bonmin.optionname` in the returned dict. Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def asdict(self) -> dict[str, float]: """Converts the Pydantic model into a dict so that Bonmin specific options are in the correct format. This means that the attributes starting with `bonmin_optionname` will be converted to keys in the format `bonmin.optionname` in the returned dict. """ output = {} for field_name, _ in BonminOptions.model_fields.items(): if (rest := field_name.split(sep="_"))[0] == "bonmin": # Convert to Bonmin specific format output[f"bonmin.{'_'.join(rest[1:])}"] = getattr(self, field_name) else: # Keep the field as is output[field_name] = getattr(self, field_name) return output ``` ### CbcOptions Bases: `BaseModel` Defines a pydantic dataclass to pass options to the CBC solver. For more information and documentation on the options, see https://github.com/coin-or/Cbc Note Not all options are available through this model. Please add options as they are needed and make a pull request. Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` class CbcOptions(BaseModel): """Defines a pydantic dataclass to pass options to the CBC solver. For more information and documentation on the options, see https://github.com/coin-or/Cbc Note: Not all options are available through this model. Please add options as they are needed and make a pull request. """ model_config = ConfigDict(frozen=True, populate_by_name=True) seconds: int = Field( description="The maximum amount of time (in seconds) the solver should run. Defaults to 600.", default=600 ) """The maximum amount of time (in seconds) the solver should run. Defaults to 600.""" threads: int = Field( description="Number of threads (cores) to use for solving the problem. Defaults to 4.", default=4 ) """Number of threads (cores) to use for solving the problem. Defaults to 4.""" log_level: int = Field( alias="logLevel", description=( "Controls the level of logging output. Values range from 0 (no output) to 5 (very detailed output)." " Defaults to 2." ), default=2, ) """Controls the level of logging output. Values range from 0 (no output) to 5 (very detailed output). Defaults to 2. """ max_solutions: int = Field( alias="maxSolutions", description="Limits the number of feasible solutions found by the solver. Defaults to 10.", default=10, ) """Limits the number of feasible solutions found by the solver. Defaults to 10.""" max_nodes: int = Field( alias="maxNodes", description="Sets the maximum number of branch-and-bound nodes to explore. Defaults to 1000.", default=1000, ) """Sets the maximum number of branch-and-bound nodes to explore. Defaults to 1000.""" ratio_gap: float = Field( alias="ratioGap", description=( "Sets the relative MIP gap (as a fraction of the optimal solution value) at which the solver will" " terminate. Defaults to 0.01." ), default=0.01, ) """Sets the relative MIP gap (as a fraction of the optimal solution value) at which the solver will terminate. Defaults to 0.01. """ absolute_gap: float = Field( alias="absoluteGap", description=( "Sets the absolute MIP gap (an absolute value) at which the solver will terminate. Defaults to 1.0." ), default=1.0, ) """Sets the absolute MIP gap (an absolute value) at which the solver will terminate. Defaults to 1.0.""" solve: str = Field( description=( "Determines the strategy to use for solving the problem (e.g., 'branchAndCut', 'tree', 'trunk')." " Defaults to 'branchAndCut'." ), default="branchAndCut", ) """Determines the strategy to use for solving the problem (e.g., 'branchAndCut', 'tree', 'trunk'). Defaults to 'branchAndCut'. """ presolve: int = Field( description="Controls the presolve level (0: no presolve, 1: default, 2: aggressive). Defaults to 2.", default=2 ) """Controls the presolve level (0: no presolve, 1: default, 2: aggressive). Defaults to 2.""" feasibility_tolerance: float = Field( alias="feasibilityTolerance", description="Sets the feasibility tolerance for constraints. Defaults to 1e-6.", default=1e-6, ) """Sets the feasibility tolerance for constraints. Defaults to 1e-6.""" integer_tolerance: float = Field( alias="integerTolerance", description="Sets the tolerance for integrality of integer variables. Defaults to 1e-5.", default=1e-5, ) """Sets the tolerance for integrality of integer variables. Defaults to 1e-5.""" ``` #### absolute_gap ``` absolute_gap: float = Field( alias="absoluteGap", description="Sets the absolute MIP gap (an absolute value) at which the solver will terminate. Defaults to 1.0.", default=1.0, ) ``` Sets the absolute MIP gap (an absolute value) at which the solver will terminate. Defaults to 1.0. #### feasibility_tolerance ``` feasibility_tolerance: float = Field( alias="feasibilityTolerance", description="Sets the feasibility tolerance for constraints. Defaults to 1e-6.", default=1e-06, ) ``` Sets the feasibility tolerance for constraints. Defaults to 1e-6. #### integer_tolerance ``` integer_tolerance: float = Field( alias="integerTolerance", description="Sets the tolerance for integrality of integer variables. Defaults to 1e-5.", default=1e-05, ) ``` Sets the tolerance for integrality of integer variables. Defaults to 1e-5. #### log_level ``` log_level: int = Field( alias="logLevel", description="Controls the level of logging output. Values range from 0 (no output) to 5 (very detailed output). Defaults to 2.", default=2, ) ``` Controls the level of logging output. Values range from 0 (no output) to 5 (very detailed output). Defaults to 2. #### max_nodes ``` max_nodes: int = Field( alias="maxNodes", description="Sets the maximum number of branch-and-bound nodes to explore. Defaults to 1000.", default=1000, ) ``` Sets the maximum number of branch-and-bound nodes to explore. Defaults to 1000. #### max_solutions ``` max_solutions: int = Field( alias="maxSolutions", description="Limits the number of feasible solutions found by the solver. Defaults to 10.", default=10, ) ``` Limits the number of feasible solutions found by the solver. Defaults to 10. #### presolve ``` presolve: int = Field( description="Controls the presolve level (0: no presolve, 1: default, 2: aggressive). Defaults to 2.", default=2, ) ``` Controls the presolve level (0: no presolve, 1: default, 2: aggressive). Defaults to 2. #### ratio_gap ``` ratio_gap: float = Field( alias="ratioGap", description="Sets the relative MIP gap (as a fraction of the optimal solution value) at which the solver will terminate. Defaults to 0.01.", default=0.01, ) ``` Sets the relative MIP gap (as a fraction of the optimal solution value) at which the solver will terminate. Defaults to 0.01. #### seconds ``` seconds: int = Field( description="The maximum amount of time (in seconds) the solver should run. Defaults to 600.", default=600, ) ``` The maximum amount of time (in seconds) the solver should run. Defaults to 600. #### solve ``` solve: str = Field( description="Determines the strategy to use for solving the problem (e.g., 'branchAndCut', 'tree', 'trunk'). Defaults to 'branchAndCut'.", default="branchAndCut", ) ``` Determines the strategy to use for solving the problem (e.g., 'branchAndCut', 'tree', 'trunk'). Defaults to 'branchAndCut'. #### threads ``` threads: int = Field( description="Number of threads (cores) to use for solving the problem. Defaults to 4.", default=4, ) ``` Number of threads (cores) to use for solving the problem. Defaults to 4. ### IpoptOptions Bases: `BaseModel` Defines a pydantic dataclass to pass options to the Ipopt solver. For more information and documentation on the options, see https://coin-or.github.io/Ipopt/ Note Not all options are available through this model. Please add options as they are needed and make a pull request. Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` class IpoptOptions(BaseModel): """Defines a pydantic dataclass to pass options to the Ipopt solver. For more information and documentation on the options, see https://coin-or.github.io/Ipopt/ Note: Not all options are available through this model. Please add options as they are needed and make a pull request. """ tol: float = Field(description="The desired relative convergence tolerance. Defaults to 1e-8.", default=1e-8) """The desired relative convergence tolerance. Defaults to 1e-8.""" max_iter: int = Field(description="Maximum number of iterations. Must be >1. Defaults to 3000.", default=3000) """Maximum number of iterations. Must be >1. Defaults to 3000.""" print_level: int = Field( description="The verbosity level of the solver's output. Ranges between 0 and 12. Defaults to 5.", default=5 ) """The verbosity level of the solver's output. Ranges between 0 and 12.""" ``` #### max_iter ``` max_iter: int = Field( description="Maximum number of iterations. Must be >1. Defaults to 3000.", default=3000, ) ``` Maximum number of iterations. Must be >1. Defaults to 3000. #### print_level ``` print_level: int = Field( description="The verbosity level of the solver's output. Ranges between 0 and 12. Defaults to 5.", default=5, ) ``` The verbosity level of the solver's output. Ranges between 0 and 12. #### tol ``` tol: float = Field( description="The desired relative convergence tolerance. Defaults to 1e-8.", default=1e-08, ) ``` The desired relative convergence tolerance. Defaults to 1e-8. ### PyomoBonminSolver Bases: `BaseSolver` Creates pyomo solvers that utilize bonmin. Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` class PyomoBonminSolver(BaseSolver): """Creates pyomo solvers that utilize bonmin.""" def __init__(self, problem: Problem, options: BonminOptions | None = _default_bonmin_options): """The solver is initialized with a problem and solver options. Suitable for mixed-integer problems. The objective function being minimized (target) and the constraint functions must be twice continuously differentiable. When the objective functions and constraints are convex, the solution is exact. When the objective or any of the constraints, or both, are non-convex, then the solution is based on heuristics. For more info about bonmin, see: https://www.coin-or.org/Bonmin/ Note: Bonmin must be installed on the system running DESDEO, and its executable must be defined in the PATH. Args: problem (Problem): the problem to be solved. options (BonminOptions, optional): options to be passed to the Bonmin solver. If `None` is passed, defaults to `_default_bonmin_options` defined in this source file. Defaults to `None`. """ if not problem.is_twice_differentiable: raise SolverError("Problem must be twice differentiable.") self.problem = problem self.evaluator = PyomoEvaluator(problem) if options is None: self.options = _default_bonmin_options else: self.options = options # Add suffix to request dual values from Bonmin self.evaluator.model.dual = pyomo.Suffix(direction=pyomo.Suffix.IMPORT) def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: the results of the optimization. """ self.evaluator.set_optimization_target(target) opt = pyomo.SolverFactory("bonmin", tee=True) # set solver options for key, value in self.options.asdict().items(): opt.options[key] = value opt_res = opt.solve(self.evaluator.model) return parse_pyomo_optimizer_results(opt_res, self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: BonminOptions | None = _default_bonmin_options, ) ``` The solver is initialized with a problem and solver options. Suitable for mixed-integer problems. The objective function being minimized (target) and the constraint functions must be twice continuously differentiable. When the objective functions and constraints are convex, the solution is exact. When the objective or any of the constraints, or both, are non-convex, then the solution is based on heuristics. For more info about bonmin, see: https://www.coin-or.org/Bonmin/ Note Bonmin must be installed on the system running DESDEO, and its executable must be defined in the PATH. Parameters: | Name | Type | Description | Default | | --------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | | `problem` | `Problem` | the problem to be solved. | *required* | | `options` | `BonminOptions` | options to be passed to the Bonmin solver. If None is passed, defaults to \_default_bonmin_options defined in this source file. Defaults to None. | `_default_bonmin_options` | Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def __init__(self, problem: Problem, options: BonminOptions | None = _default_bonmin_options): """The solver is initialized with a problem and solver options. Suitable for mixed-integer problems. The objective function being minimized (target) and the constraint functions must be twice continuously differentiable. When the objective functions and constraints are convex, the solution is exact. When the objective or any of the constraints, or both, are non-convex, then the solution is based on heuristics. For more info about bonmin, see: https://www.coin-or.org/Bonmin/ Note: Bonmin must be installed on the system running DESDEO, and its executable must be defined in the PATH. Args: problem (Problem): the problem to be solved. options (BonminOptions, optional): options to be passed to the Bonmin solver. If `None` is passed, defaults to `_default_bonmin_options` defined in this source file. Defaults to `None`. """ if not problem.is_twice_differentiable: raise SolverError("Problem must be twice differentiable.") self.problem = problem self.evaluator = PyomoEvaluator(problem) if options is None: self.options = _default_bonmin_options else: self.options = options # Add suffix to request dual values from Bonmin self.evaluator.model.dual = pyomo.Suffix(direction=pyomo.Suffix.IMPORT) ``` #### solve ``` solve(target: str) -> SolverResults ``` Solve the problem for a given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | the symbol of the objective function to be optimized. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | -------------------------------- | | `SolverResults` | `SolverResults` | the results of the optimization. | Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: the results of the optimization. """ self.evaluator.set_optimization_target(target) opt = pyomo.SolverFactory("bonmin", tee=True) # set solver options for key, value in self.options.asdict().items(): opt.options[key] = value opt_res = opt.solve(self.evaluator.model) return parse_pyomo_optimizer_results(opt_res, self.problem, self.evaluator) ``` ### PyomoCBCSolver Bases: `BaseSolver` Create a pyomo solver that utilizes CBC. Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` class PyomoCBCSolver(BaseSolver): """Create a pyomo solver that utilizes CBC.""" def __init__(self, problem: Problem, options: CbcOptions | None = _default_cbc_options): """The solver is initialized with a problem and solver options. Suitable for combinatorial and large-scale mixed-integer linear problems. For more information, see https://coin-or.github.io/Ipopt/ Note: CBC must be installed on the system running DESDEO, and its executable must be defined in the PATH. Args: problem (Problem): the problem being solved. options (CbcOptions, optional): options to be passed to the CBC solver. If `None` is passed, defaults to `_default_cbc_options` defined in this source file. Defaults to `None`. """ if not problem.is_linear: raise SolverError("Nonlinear problems not supported.") self.problem = problem self.evaluator = PyomoEvaluator(problem) if options is None: self.options = _default_cbc_options else: self.options = options def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: results of the Optimization. """ self.evaluator.set_optimization_target(target) opt = pyomo.SolverFactory("cbc", tee=True, options=self.options.model_dump()) opt_res = opt.solve(self.evaluator.model) return parse_pyomo_optimizer_results(opt_res, self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: CbcOptions | None = _default_cbc_options, ) ``` The solver is initialized with a problem and solver options. Suitable for combinatorial and large-scale mixed-integer linear problems. For more information, see https://coin-or.github.io/Ipopt/ Note CBC must be installed on the system running DESDEO, and its executable must be defined in the PATH. Parameters: | Name | Type | Description | Default | | --------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | | `problem` | `Problem` | the problem being solved. | *required* | | `options` | `CbcOptions` | options to be passed to the CBC solver. If None is passed, defaults to \_default_cbc_options defined in this source file. Defaults to None. | `_default_cbc_options` | Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def __init__(self, problem: Problem, options: CbcOptions | None = _default_cbc_options): """The solver is initialized with a problem and solver options. Suitable for combinatorial and large-scale mixed-integer linear problems. For more information, see https://coin-or.github.io/Ipopt/ Note: CBC must be installed on the system running DESDEO, and its executable must be defined in the PATH. Args: problem (Problem): the problem being solved. options (CbcOptions, optional): options to be passed to the CBC solver. If `None` is passed, defaults to `_default_cbc_options` defined in this source file. Defaults to `None`. """ if not problem.is_linear: raise SolverError("Nonlinear problems not supported.") self.problem = problem self.evaluator = PyomoEvaluator(problem) if options is None: self.options = _default_cbc_options else: self.options = options ``` #### solve ``` solve(target: str) -> SolverResults ``` Solve the problem for a given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | the symbol of the objective function to be optimized. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ---------------------------- | | `SolverResults` | `SolverResults` | results of the Optimization. | Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: results of the Optimization. """ self.evaluator.set_optimization_target(target) opt = pyomo.SolverFactory("cbc", tee=True, options=self.options.model_dump()) opt_res = opt.solve(self.evaluator.model) return parse_pyomo_optimizer_results(opt_res, self.problem, self.evaluator) ``` ### PyomoGurobiSolver Bases: `BaseSolver` Creates a pyomo solver that utilized Gurobi. Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` class PyomoGurobiSolver(BaseSolver): """Creates a pyomo solver that utilized Gurobi.""" def __init__(self, problem: Problem, options: dict[str, any] | None = None): """Creates a pyomo solver that utilizes gurobi. You need to have gurobi installed on your system for this to work. Suitable for solving mixed-integer linear and quadratic optimization problems. Args: problem (Problem): the problem to be solved. options (GurobiOptions): Dictionary of Gurobi parameters to set. This is passed to pyomo as is, so it works the same as options would for calling pyomo SolverFactory directly. See https://www.gurobi.com/documentation/current/refman/parameters.html for information on the available options """ self.problem = problem self.evaluator = PyomoEvaluator(problem) if options is None: self.options = {} else: self.options = options def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: the results of the optimization. """ self.evaluator.set_optimization_target(target) with pyomo.SolverFactory("gurobi", solver_io="python") as opt: opt_res = opt.solve(self.evaluator.model) return parse_pyomo_optimizer_results(opt_res, self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: dict[str, any] | None = None ) ``` Creates a pyomo solver that utilizes gurobi. You need to have gurobi installed on your system for this to work. Suitable for solving mixed-integer linear and quadratic optimization problems. Parameters: | Name | Type | Description | Default | | --------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem to be solved. | *required* | | `options` | `GurobiOptions` | Dictionary of Gurobi parameters to set. This is passed to pyomo as is, so it works the same as options would for calling pyomo SolverFactory directly. See https://www.gurobi.com/documentation/current/refman/parameters.html for information on the available options | `None` | Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def __init__(self, problem: Problem, options: dict[str, any] | None = None): """Creates a pyomo solver that utilizes gurobi. You need to have gurobi installed on your system for this to work. Suitable for solving mixed-integer linear and quadratic optimization problems. Args: problem (Problem): the problem to be solved. options (GurobiOptions): Dictionary of Gurobi parameters to set. This is passed to pyomo as is, so it works the same as options would for calling pyomo SolverFactory directly. See https://www.gurobi.com/documentation/current/refman/parameters.html for information on the available options """ self.problem = problem self.evaluator = PyomoEvaluator(problem) if options is None: self.options = {} else: self.options = options ``` #### solve ``` solve(target: str) -> SolverResults ``` Solve the problem for a given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | the symbol of the objective function to be optimized. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | -------------------------------- | | `SolverResults` | `SolverResults` | the results of the optimization. | Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: the results of the optimization. """ self.evaluator.set_optimization_target(target) with pyomo.SolverFactory("gurobi", solver_io="python") as opt: opt_res = opt.solve(self.evaluator.model) return parse_pyomo_optimizer_results(opt_res, self.problem, self.evaluator) ``` ### PyomoIpoptSolver Bases: `BaseSolver` Create a pyomo solver that utilizes Ipopt. Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` class PyomoIpoptSolver(BaseSolver): """Create a pyomo solver that utilizes Ipopt.""" def __init__(self, problem: Problem, options: IpoptOptions | None = _default_ipopt_options): """The solver is initialized with a problem and solver options. Suitable for non-linear, twice differentiable constrained problems. The problem may be convex or non-convex. For more information, see https://coin-or.github.io/Ipopt/ Note: Ipopt must be installed on the system running DESDEO, and its executable must be defined in the PATH. Args: problem (Problem): the problem being solved. options (IpoptOptions, optional): options to be passed to the Ipopt solver. If `None` is passed, defaults to `_default_ipopt_options` defined in this source file. Defaults to `None`. """ if not problem.is_twice_differentiable: raise SolverError("Problem must be twice differentiable.") self.problem = problem self.evaluator = PyomoEvaluator(problem) if options is None: self.options = _default_ipopt_options else: self.options = options # Add suffix to request dual values from Ipopt self.evaluator.model.dual = pyomo.Suffix(direction=pyomo.Suffix.IMPORT) def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: results of the Optimization. """ self.evaluator.set_optimization_target(target) opt = pyomo.SolverFactory("ipopt", tee=True, options=self.options.model_dump()) opt_res = opt.solve(self.evaluator.model) return parse_pyomo_optimizer_results(opt_res, self.problem, self.evaluator) ``` #### __init__ ``` __init__( problem: Problem, options: IpoptOptions | None = _default_ipopt_options, ) ``` The solver is initialized with a problem and solver options. Suitable for non-linear, twice differentiable constrained problems. The problem may be convex or non-convex. For more information, see https://coin-or.github.io/Ipopt/ Note Ipopt must be installed on the system running DESDEO, and its executable must be defined in the PATH. Parameters: | Name | Type | Description | Default | | --------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ | | `problem` | `Problem` | the problem being solved. | *required* | | `options` | `IpoptOptions` | options to be passed to the Ipopt solver. If None is passed, defaults to \_default_ipopt_options defined in this source file. Defaults to None. | `_default_ipopt_options` | Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def __init__(self, problem: Problem, options: IpoptOptions | None = _default_ipopt_options): """The solver is initialized with a problem and solver options. Suitable for non-linear, twice differentiable constrained problems. The problem may be convex or non-convex. For more information, see https://coin-or.github.io/Ipopt/ Note: Ipopt must be installed on the system running DESDEO, and its executable must be defined in the PATH. Args: problem (Problem): the problem being solved. options (IpoptOptions, optional): options to be passed to the Ipopt solver. If `None` is passed, defaults to `_default_ipopt_options` defined in this source file. Defaults to `None`. """ if not problem.is_twice_differentiable: raise SolverError("Problem must be twice differentiable.") self.problem = problem self.evaluator = PyomoEvaluator(problem) if options is None: self.options = _default_ipopt_options else: self.options = options # Add suffix to request dual values from Ipopt self.evaluator.model.dual = pyomo.Suffix(direction=pyomo.Suffix.IMPORT) ``` #### solve ``` solve(target: str) -> SolverResults ``` Solve the problem for a given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | the symbol of the objective function to be optimized. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ---------------------------- | | `SolverResults` | `SolverResults` | results of the Optimization. | Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def solve(self, target: str) -> SolverResults: """Solve the problem for a given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: results of the Optimization. """ self.evaluator.set_optimization_target(target) opt = pyomo.SolverFactory("ipopt", tee=True, options=self.options.model_dump()) opt_res = opt.solve(self.evaluator.model) return parse_pyomo_optimizer_results(opt_res, self.problem, self.evaluator) ``` ### parse_pyomo_optimizer_results ``` parse_pyomo_optimizer_results( opt_res: SolverResults, problem: Problem, evaluator: PyomoEvaluator, ) -> SolverResults ``` Parses pyomo SolverResults into DESDEO SolverResults. Parameters: | Name | Type | Description | Default | | ----------- | ---------------- | ------------------------------------------------------- | ---------- | | `opt_res` | `SolverResults` | the pyomo solver results. | *required* | | `problem` | `Problem` | the problem being solved. | *required* | | `evaluator` | `PyomoEvaluator` | the evaluator utilized to get the pyomo solver results. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ---------------------- | | `SolverResults` | `SolverResults` | DESDEO solver results. | Source code in `desdeo/tools/pyomo_solver_interfaces.py` ``` def parse_pyomo_optimizer_results( # noqa: C901 opt_res: _pyomo_SolverResults, problem: Problem, evaluator: PyomoEvaluator ) -> SolverResults: """Parses pyomo SolverResults into DESDEO SolverResults. Args: opt_res (SolverResults): the pyomo solver results. problem (Problem): the problem being solved. evaluator (PyomoEvaluator): the evaluator utilized to get the pyomo solver results. Returns: SolverResults: DESDEO solver results. """ results = evaluator.get_values() variable_values = {} for var in problem.variables: if isinstance(var, TensorVariable): # handle tensor variables # 1-indexing in Pyomo... values_list = np.zeros(var.shape) for indices in itertools.product(*(range(1, dim + 1) for dim in var.shape)): values_list[*[idx - 1 for idx in indices]] = results[var.symbol][ indices if len(indices) > 1 else indices[0] ] variable_values[var.symbol] = values_list.tolist() else: # variable_values = {var.symbol: results[var.symbol] for var in problem.variables} variable_values[var.symbol] = results[var.symbol] objective_values = {obj.symbol: results[obj.symbol] for obj in problem.objectives} constraint_values = ( {con.symbol: results[con.symbol] for con in problem.constraints} if problem.constraints else None ) # handle constraint, which might be multi-valued if problem.constraints is not None: constraint_values = {} for con in problem.constraints: result = results[con.symbol] if isinstance(result, dict): # multi-valued indices = list(getattr(evaluator.model, con.symbol).keys()) if indices and isinstance(indices[0], int): # 1-D constraint indexed by RangeSet — keys are plain integers values_list = np.zeros(len(indices)) for idx in indices: values_list[idx - 1] = result[idx] else: # multi-D constraint — keys are tuples shape = tuple(len({idx[k] for idx in indices}) for k in range(len(indices[0]))) values_list = np.zeros(shape) for idx in indices: values_list[*[i - 1 for i in idx]] = result[idx] constraint_values[con.symbol] = values_list.tolist() else: # scalar-valued constraint_values[con.symbol] = result else: constraint_values = None extra_func_values = ( {extra.symbol: results[extra.symbol] for extra in problem.extra_funcs} if problem.extra_funcs is not None else None ) scalarization_values = ( {scal.symbol: results[scal.symbol] for scal in problem.scalarization_funcs} if problem.scalarization_funcs is not None else None ) # Extract Lagrange multipliers with error handling lagrange_multipliers = None if problem.constraints: try: if hasattr(evaluator.model, "dual") and evaluator.model.dual: lagrange_multipliers = {} for con in problem.constraints: try: constraint_obj = getattr(evaluator.model, con.symbol) if constraint_obj in evaluator.model.dual: lagrange_multipliers["mu_" + con.symbol] = evaluator.model.dual[constraint_obj] except (AttributeError, KeyError): continue if not lagrange_multipliers: lagrange_multipliers = None except (AttributeError, KeyError): lagrange_multipliers = None success = ( opt_res.solver.status == _pyomo_SolverStatus.ok and opt_res.solver.termination_condition == _pyomo_TerminationCondition.optimal ) msg = ( f"Pyomo solver status is: '{opt_res.solver.status}', with termination condition: " f"'{opt_res.solver.termination_condition}'." ) return SolverResults( optimal_variables=variable_values, optimal_objectives=objective_values, constraint_values=constraint_values, extra_func_values=extra_func_values, scalarization_values=scalarization_values, lagrange_multipliers=lagrange_multipliers, success=success, message=msg, ) ``` ## Proximal solver Defines solvers meant to be utilized with Problems with discrete representations. ### ProximalSolver Bases: `BaseSolver` Creates a solver that finds the closest solution given a fully discrete problem. Note This solver is extremely naive. It will optimize the problem and the result will be a point defined for a discrete problem that is closest (Euclidean distance) to the optimum. The result may be wildly inaccurate depending on how representative the discrete points are of the original problem. Source code in `desdeo/tools/proximal_solver.py` ``` class ProximalSolver(BaseSolver): """Creates a solver that finds the closest solution given a fully discrete problem. Note: This solver is extremely naive. It will optimize the problem and the result will be a point defined for a discrete problem that is closest (Euclidean distance) to the optimum. The result may be wildly inaccurate depending on how representative the discrete points are of the original problem. """ def __init__(self, problem: Problem, kwargs: dict | None = None): """Creates a solver that assumes the problem being a fully discrete one. Assumes that problem has only data-based objectives and a discrete definition that fully defines all the objectives. Args: problem (Problem): the problem being solved. kwargs (Optional[dict]): optional keyword arguments. Not used right now, but kept here for compatibility reasons. Defaults to None. """ for obj in problem.objectives: if obj.objective_type is not ObjectiveTypeEnum.data_based: raise SolverError(f"All objectives must be data-based {obj.symbol}.") if problem.discrete_representation is None: raise SolverError("Problem must have a discrete representation defined.") self.problem = problem self.evaluator = PolarsEvaluator(problem, evaluator_mode=PolarsEvaluatorModesEnum.discrete) def solve(self, target: str) -> SolverResults: """Solve the problem for the given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: the results fo the optimization. """ results_df = self.evaluator.evaluate() # check constraint values if problem has constraints if self.problem.constraints is not None: cons_condition = pl.lit(True) # noqa: FBT003 for constraint in self.problem.constraints: cons_condition = cons_condition & (results_df[constraint.symbol] <= 0) results_df = results_df.filter(cons_condition) # find the row with the minimum value in the 'target' column closest = results_df.sort(target).head(1) # extract relevant results, extract them as dict for easier jsonification variable_values = {variable.symbol: closest[variable.symbol][0] for variable in self.problem.variables} objective_values = {objective.symbol: closest[objective.symbol][0] for objective in self.problem.objectives} constraint_values = ( {constraint.symbol: closest[constraint.symbol][0] for constraint in self.problem.constraints} if self.problem.constraints is not None else None ) extra_func_values = ( {extra.symbol: closest[extra.symbol][0] for extra in self.problem.extra_funcs} if self.problem.extra_funcs is not None else None ) scalarization_values = ( {scal.symbol: closest[scal.symbol][0] for scal in self.problem.scalarization_funcs} if self.problem.scalarization_funcs is not None else None ) message = f"Optimal value found from tabular data minimizing the column '{target}'." success = True # wrap results and return them return SolverResults( optimal_variables=variable_values, optimal_objectives=objective_values, constraint_values=constraint_values, extra_func_values=extra_func_values, scalarization_values=scalarization_values, success=success, message=message, ) ``` #### __init__ ``` __init__(problem: Problem, kwargs: dict | None = None) ``` Creates a solver that assumes the problem being a fully discrete one. Assumes that problem has only data-based objectives and a discrete definition that fully defines all the objectives. Parameters: | Name | Type | Description | Default | | --------- | ---------------- | ---------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the problem being solved. | *required* | | `kwargs` | `Optional[dict]` | optional keyword arguments. Not used right now, but kept here for compatibility reasons. Defaults to None. | `None` | Source code in `desdeo/tools/proximal_solver.py` ``` def __init__(self, problem: Problem, kwargs: dict | None = None): """Creates a solver that assumes the problem being a fully discrete one. Assumes that problem has only data-based objectives and a discrete definition that fully defines all the objectives. Args: problem (Problem): the problem being solved. kwargs (Optional[dict]): optional keyword arguments. Not used right now, but kept here for compatibility reasons. Defaults to None. """ for obj in problem.objectives: if obj.objective_type is not ObjectiveTypeEnum.data_based: raise SolverError(f"All objectives must be data-based {obj.symbol}.") if problem.discrete_representation is None: raise SolverError("Problem must have a discrete representation defined.") self.problem = problem self.evaluator = PolarsEvaluator(problem, evaluator_mode=PolarsEvaluatorModesEnum.discrete) ``` #### solve ``` solve(target: str) -> SolverResults ``` Solve the problem for the given target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | the symbol of the objective function to be optimized. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | -------------------------------- | | `SolverResults` | `SolverResults` | the results fo the optimization. | Source code in `desdeo/tools/proximal_solver.py` ``` def solve(self, target: str) -> SolverResults: """Solve the problem for the given target. Args: target (str): the symbol of the objective function to be optimized. Returns: SolverResults: the results fo the optimization. """ results_df = self.evaluator.evaluate() # check constraint values if problem has constraints if self.problem.constraints is not None: cons_condition = pl.lit(True) # noqa: FBT003 for constraint in self.problem.constraints: cons_condition = cons_condition & (results_df[constraint.symbol] <= 0) results_df = results_df.filter(cons_condition) # find the row with the minimum value in the 'target' column closest = results_df.sort(target).head(1) # extract relevant results, extract them as dict for easier jsonification variable_values = {variable.symbol: closest[variable.symbol][0] for variable in self.problem.variables} objective_values = {objective.symbol: closest[objective.symbol][0] for objective in self.problem.objectives} constraint_values = ( {constraint.symbol: closest[constraint.symbol][0] for constraint in self.problem.constraints} if self.problem.constraints is not None else None ) extra_func_values = ( {extra.symbol: closest[extra.symbol][0] for extra in self.problem.extra_funcs} if self.problem.extra_funcs is not None else None ) scalarization_values = ( {scal.symbol: closest[scal.symbol][0] for scal in self.problem.scalarization_funcs} if self.problem.scalarization_funcs is not None else None ) message = f"Optimal value found from tabular data minimizing the column '{target}'." success = True # wrap results and return them return SolverResults( optimal_variables=variable_values, optimal_objectives=objective_values, constraint_values=constraint_values, extra_func_values=extra_func_values, scalarization_values=scalarization_values, success=success, message=message, ) ``` ## Scenario tools Tools for constructing and solving scenario-based optimization problems. ### \_build_constant_maps ``` _build_constant_maps( leaf_scenarios: list[str], scenario_problems: dict[str, Problem], ) -> tuple[ dict[str, dict[str, str]], dict[str, Constant | TensorConstant], ] ``` Build per-leaf constant rename maps and the combined constant dict. Constants whose value is the same in every leaf keep their original symbol. Constants that differ across leaves are renamed to `symbol_leaf`. Returns: | Name | Type | Description | | -------------------- | --------------------------- | ----------------------------------- | | `const_maps` | `dict[str, dict[str, str]]` | {leaf -> {original_sym -> new_sym}} | | `combined_constants` | \`dict\[str, Constant | TensorConstant\]\` | Source code in `desdeo/tools/scenarios.py` ``` def _build_constant_maps( leaf_scenarios: list[str], scenario_problems: dict[str, Problem], ) -> tuple[dict[str, dict[str, str]], dict[str, Constant | TensorConstant]]: """Build per-leaf constant rename maps and the combined constant dict. Constants whose value is the same in every leaf keep their original symbol. Constants that differ across leaves are renamed to ``symbol_leaf``. Returns: const_maps: {leaf -> {original_sym -> new_sym}} combined_constants: {new_sym -> Constant | TensorConstant} """ const_per_leaf: dict[str, dict[str, Constant | TensorConstant]] = { leaf: {c.symbol: c for c in (scenario_problems[leaf].constants or [])} for leaf in leaf_scenarios } all_const_syms: set[str] = {sym for lc in const_per_leaf.values() for sym in lc} const_maps: dict[str, dict[str, str]] = {leaf: {} for leaf in leaf_scenarios} combined_constants: dict[str, Constant | TensorConstant] = {} for sym in all_const_syms: values = { leaf: _constant_value_key(const_per_leaf[leaf][sym]) for leaf in leaf_scenarios if sym in const_per_leaf[leaf] } if len(set(values.values())) <= 1: for leaf in leaf_scenarios: const_maps[leaf][sym] = sym first = next( (const_per_leaf[leaf][sym] for leaf in leaf_scenarios if sym in const_per_leaf[leaf]), None, ) if first is not None: combined_constants[sym] = first else: for leaf in leaf_scenarios: if sym in const_per_leaf[leaf]: new_sym = f"{leaf}_{sym}" const_maps[leaf][sym] = new_sym combined_constants[new_sym] = const_per_leaf[leaf][sym].model_copy(update={"symbol": new_sym}) return const_maps, combined_constants ``` ### \_build_parent_map ``` _build_parent_map( scenario_tree: dict[str, list[str]], ) -> dict[str, str] ``` Return a mapping from each node to its parent node. Source code in `desdeo/tools/scenarios.py` ``` def _build_parent_map(scenario_tree: dict[str, list[str]]) -> dict[str, str]: """Return a mapping from each node to its parent node.""" parent: dict[str, str] = {} for node, children in scenario_tree.items(): for child in children: parent[child] = node return parent ``` ### \_build_variable_maps ``` _build_variable_maps( scenario_model: ScenarioModel, leaf_scenarios: list[str], parent_map: dict[str, str], scenario_problems: dict[str, Problem], ) -> tuple[ dict[str, dict[str, str]], dict[str, Variable | TensorVariable], ] ``` Build per-leaf variable rename maps and the combined variable dict. Returns: | Name | Type | Description | | -------------------- | --------------------------- | ----------------------------------- | | `var_maps` | `dict[str, dict[str, str]]` | {leaf -> {original_sym -> new_sym}} | | `combined_variables` | \`dict\[str, Variable | TensorVariable\]\` | Source code in `desdeo/tools/scenarios.py` ``` def _build_variable_maps( scenario_model: "ScenarioModel", leaf_scenarios: list[str], parent_map: dict[str, str], scenario_problems: dict[str, Problem], ) -> tuple[dict[str, dict[str, str]], dict[str, Variable | TensorVariable]]: """Build per-leaf variable rename maps and the combined variable dict. Returns: var_maps: {leaf -> {original_sym -> new_sym}} combined_variables: {new_sym -> Variable | TensorVariable} """ # Each leaf's own variables, so variables added only by scenario pools are renamed too. var_maps: dict[str, dict[str, str]] = { leaf: { v.symbol: _new_variable_symbol(v.symbol, leaf, scenario_model.anticipation_stop, parent_map) for v in scenario_problems[leaf].variables } for leaf in leaf_scenarios } combined_variables: dict[str, Variable | TensorVariable] = {} for leaf in leaf_scenarios: for var in scenario_problems[leaf].variables: new_sym = var_maps[leaf][var.symbol] if new_sym not in combined_variables: combined_variables[new_sym] = var.model_copy( update={"symbol": new_sym, "name": f"{var.name} ({new_sym})"} ) return var_maps, combined_variables ``` ### \_combine_elements ``` _combine_elements( leaf_scenarios: list[str], scenario_problems: dict[str, Problem], var_maps: dict[str, dict[str, str]], const_maps: dict[str, dict[str, str]], get_list: callable, make_update: callable, extra_leaf_maps: dict[str, dict[str, str]] | None = None, ) -> tuple[list | None, dict[str, dict[str, str]]] ``` Build a combined list for one element type across all leaf scenarios. Elements whose renamed func string is identical across every leaf that carries them are kept as a single shared element (original symbol). All others get a per-leaf prefix `leaf_symbol`. Parameters: | Name | Type | Description | Default | | ------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `leaf_scenarios` | `list[str]` | ordered list of leaf scenario names. | *required* | | `scenario_problems` | `dict[str, Problem]` | pre-computed {leaf -> Problem} mapping. | *required* | | `var_maps` | `dict[str, dict[str, str]]` | per-leaf variable rename maps {leaf -> {orig_sym -> new_sym}}. | *required* | | `const_maps` | `dict[str, dict[str, str]]` | per-leaf constant rename maps {leaf -> {orig_sym -> new_sym}}. | *required* | | `get_list` | `callable` | callable(Problem) -> list | None of elements. | | `make_update` | `callable` | callable(elem, new_func, leaf) -> dict for model_copy. leaf is the scenario name for per-leaf elements, or None for shared ones. new_sym is derived inside as f"{leaf}\_{elem.symbol}" or elem.symbol. | *required* | | `extra_leaf_maps` | \`dict\[str, dict[str, str]\] | None\` | optional additional per-leaf rename maps merged into the leaf_map before renaming expressions. Useful for passing objective-symbol renames (including \_min versions) when processing scalarization functions and constraints. | Returns: | Type | Description | | ------------- | ------------------------------------- | | \`tuple\[list | None, dict\[str, dict[str, str]\]\]\` | Source code in `desdeo/tools/scenarios.py` ``` def _combine_elements( leaf_scenarios: list[str], scenario_problems: dict[str, Problem], var_maps: dict[str, dict[str, str]], const_maps: dict[str, dict[str, str]], get_list: callable, make_update: callable, extra_leaf_maps: "dict[str, dict[str, str]] | None" = None, ) -> tuple[list | None, dict[str, dict[str, str]]]: """Build a combined list for one element type across all leaf scenarios. Elements whose renamed func string is identical across every leaf that carries them are kept as a single shared element (original symbol). All others get a per-leaf prefix ``leaf_symbol``. Args: leaf_scenarios: ordered list of leaf scenario names. scenario_problems: pre-computed {leaf -> Problem} mapping. var_maps: per-leaf variable rename maps {leaf -> {orig_sym -> new_sym}}. const_maps: per-leaf constant rename maps {leaf -> {orig_sym -> new_sym}}. get_list: callable(Problem) -> list | None of elements. make_update: callable(elem, new_func, leaf) -> dict for model_copy. ``leaf`` is the scenario name for per-leaf elements, or ``None`` for shared ones. ``new_sym`` is derived inside as ``f"{leaf}_{elem.symbol}"`` or ``elem.symbol``. extra_leaf_maps: optional additional per-leaf rename maps merged into the leaf_map before renaming expressions. Useful for passing objective-symbol renames (including ``_min`` versions) when processing scalarization functions and constraints. Returns: A tuple of (combined list or None, symbol map). The symbol map has the original symbol as key and a {leaf -> new_symbol} dict as value. A shared element maps every leaf to the original symbol; otherwise each leaf that carries the element maps to its prefixed copy and leaves that do not carry it are absent from the map. """ combined: list = [] seen: set[str] = set() symbol_map: dict[str, dict[str, str]] = {} # Elements are processed, and therefore appended to the combined problem, in the order # they are declared. Since an element may only reference elements that appear before # it, that order is part of the combined problem's meaning and must not vary. all_syms = dict.fromkeys( elem.symbol for leaf in leaf_scenarios for elem in (get_list(scenario_problems[leaf]) or []) ) # Renames for elements of this same kind that have already been combined. An element # may reference one declared before it, and that reference has to point at the earlier # element's per-leaf copy, exactly as references to variables and earlier kinds do. own_maps: dict[str, dict[str, str]] = {leaf: {} for leaf in leaf_scenarios} for sym in all_syms: renamed: dict[str, str] = {} for leaf in leaf_scenarios: match = next( (e for e in (get_list(scenario_problems[leaf]) or []) if e.symbol == sym), None, ) if match is None: continue leaf_map = { **var_maps[leaf], **const_maps[leaf], **(extra_leaf_maps[leaf] if extra_leaf_maps else {}), **own_maps[leaf], } renamed[leaf] = _rename_symbols(match.func, leaf_map) is_shared = len({str(v) for v in renamed.values()}) == 1 and len(renamed) == len(leaf_scenarios) if is_shared: first_leaf = next(iter(renamed)) symbol_map[sym] = dict.fromkeys(leaf_scenarios, sym) entries = [(sym, first_leaf, renamed[first_leaf], None)] else: # Leaves that do not carry the element get no entry at all: there is no # combined element for them, so any symbol here would name nothing. symbol_map[sym] = {leaf: f"{leaf}_{sym}" for leaf in leaf_scenarios if leaf in renamed} # A per-leaf copy is renamed, so later elements referencing it must follow. # A shared element keeps its original symbol and needs no entry here. for leaf in renamed: own_maps[leaf][sym] = f"{leaf}_{sym}" own_maps[leaf][f"{sym}_min"] = f"{leaf}_{sym}_min" entries = [(f"{leaf}_{sym}", leaf, new_func, leaf) for leaf, new_func in renamed.items()] for new_sym, src_leaf, new_func, name_leaf in entries: if new_sym not in seen: seen.add(new_sym) elem = next(e for e in (get_list(scenario_problems[src_leaf]) or []) if e.symbol == sym) combined.append(elem.model_copy(update=make_update(elem, new_func, name_leaf))) return combined or None, symbol_map ``` ### \_constant_value_key ``` _constant_value_key( const: Constant | TensorConstant, ) -> Any ``` Return a hashable representation of a constant's value(s), for equality comparison. `Constant` stores a single scalar in `.value`. `TensorConstant` stores its data in `.values` (plural) instead and has no `.value` attribute at all, so it must be read via `get_values()` and made hashable. Source code in `desdeo/tools/scenarios.py` ``` def _constant_value_key(const: Constant | TensorConstant) -> Any: """Return a hashable representation of a constant's value(s), for equality comparison. ``Constant`` stores a single scalar in ``.value``. ``TensorConstant`` stores its data in ``.values`` (plural) instead and has no ``.value`` attribute at all, so it must be read via ``get_values()`` and made hashable. """ if isinstance(const, TensorConstant): return _to_hashable(const.get_values()) return const.value ``` ### \_longest_common_name ``` _longest_common_name( names: list[str], fallback: str ) -> str ``` Return the longest common substring across all names, stripped of edge separators. Falls back to *fallback* when the list is empty or no non-empty common substring exists. Source code in `desdeo/tools/scenarios.py` ``` def _longest_common_name(names: "list[str]", fallback: str) -> str: """Return the longest common substring across all names, stripped of edge separators. Falls back to *fallback* when the list is empty or no non-empty common substring exists. """ if not names: return fallback shortest = min(names, key=len) for length in range(len(shortest), 0, -1): for start in range(len(shortest) - length + 1): candidate = shortest[start : start + length] if all(candidate in name for name in names): stripped = candidate.strip("_- .") if stripped: return stripped return fallback ``` ### \_new_variable_symbol ``` _new_variable_symbol( var_sym: str, leaf: str, anticipation_stop: dict[str, list[str]], parent_map: dict[str, str], ) -> str ``` Return the combined-problem symbol for a variable in a given leaf scenario. Walks from ROOT toward the leaf. The first (highest) ancestor where the variable appears in anticipation_stop determines sharing: - ROOT -> all scenarios share one copy; original symbol is kept. - Other -> all leaves under that node share one copy; symbol gets that node name as prefix. - None -> fully independent per leaf; symbol gets the leaf name as prefix. Source code in `desdeo/tools/scenarios.py` ``` def _new_variable_symbol( var_sym: str, leaf: str, anticipation_stop: dict[str, list[str]], parent_map: dict[str, str], ) -> str: """Return the combined-problem symbol for a variable in a given leaf scenario. Walks from ROOT toward the leaf. The first (highest) ancestor where the variable appears in anticipation_stop determines sharing: - ROOT -> all scenarios share one copy; original symbol is kept. - Other -> all leaves under that node share one copy; symbol gets that node name as prefix. - None -> fully independent per leaf; symbol gets the leaf name as prefix. """ for node in _path_from_root(leaf, parent_map): if var_sym in anticipation_stop.get(node, []): return var_sym if node == "ROOT" else f"{node}_{var_sym}" return f"{leaf}_{var_sym}" ``` ### \_path_from_root ``` _path_from_root( node: str, parent_map: dict[str, str] ) -> list[str] ``` Return the path [ROOT, ..., node] inclusive of both ends. Source code in `desdeo/tools/scenarios.py` ``` def _path_from_root(node: str, parent_map: dict[str, str]) -> list[str]: """Return the path [ROOT, ..., node] inclusive of both ends.""" path: list[str] = [] current: str | None = node while current is not None: path.append(current) current = parent_map.get(current) path.reverse() return path ``` ### \_pool_names_for ``` _pool_names_for( scenario_model: ScenarioModel, found_type: str, sym: str, per_leaf: dict[str, str], ) -> list[str] ``` Collect distinct pool-element names for *sym* across the leaves in *per_leaf*. Source code in `desdeo/tools/scenarios.py` ``` def _pool_names_for( scenario_model: "ScenarioModel", found_type: str, sym: str, per_leaf: "dict[str, str]", ) -> "list[str]": """Collect distinct pool-element names for *sym* across the leaves in *per_leaf*.""" pool: tuple = getattr(scenario_model, found_type, ()) seen: set[int] = set() names: list[str] = [] for leaf_name in per_leaf: scenario = scenario_model.scenarios.get(leaf_name) if scenario is None: continue elem_map: dict[str, int] = getattr(scenario, found_type, {}) if sym in elem_map: idx = elem_map[sym] if idx not in seen and idx < len(pool): seen.add(idx) name = getattr(pool[idx], "name", None) if name: names.append(name) return names ``` ### \_rename_in_mathjson ``` _rename_in_mathjson(node, symbol_map: dict[str, str]) ``` Recursively rename symbol strings in a MathJSON node. Source code in `desdeo/tools/scenarios.py` ``` def _rename_in_mathjson(node, symbol_map: dict[str, str]): """Recursively rename symbol strings in a MathJSON node.""" if isinstance(node, str): return node if node in _RESERVED else symbol_map.get(node, node) if isinstance(node, list): return [_rename_in_mathjson(child, symbol_map) for child in node] return node # int / float ``` ### \_rename_symbols ``` _rename_symbols( expr: str | list, symbol_map: dict[str, str] ) -> list ``` Rename symbols in a MathJSON expression (list) or infix string. Walks the MathJSON tree and substitutes every string leaf that is not a known operator keyword. If `expr` is a plain infix string it is first parsed to MathJSON, then the renaming is applied. The returned value is always a MathJSON list, which Pydantic's `parse_infix_to_func` validator accepts directly without re-parsing. Source code in `desdeo/tools/scenarios.py` ``` def _rename_symbols(expr: str | list, symbol_map: dict[str, str]) -> list: """Rename symbols in a MathJSON expression (list) or infix string. Walks the MathJSON tree and substitutes every string leaf that is not a known operator keyword. If ``expr`` is a plain infix string it is first parsed to MathJSON, then the renaming is applied. The returned value is always a MathJSON list, which Pydantic's ``parse_infix_to_func`` validator accepts directly without re-parsing. """ if isinstance(expr, str): expr = _parser.parse(expr) return _rename_in_mathjson(expr, symbol_map) ``` ### \_symbols_in ``` _symbols_in(node) -> set[str] ``` Collect every symbol referenced in a MathJSON node, ignoring operator keywords. Source code in `desdeo/tools/scenarios.py` ``` def _symbols_in(node) -> set[str]: """Collect every symbol referenced in a MathJSON node, ignoring operator keywords.""" if isinstance(node, str): return set() if node in _RESERVED else {node} if isinstance(node, list): return {symbol for child in node for symbol in _symbols_in(child)} return set() ``` ### \_to_hashable ``` _to_hashable(value: Any) -> Any ``` Recursively convert a (possibly nested) list into a tuple so it can go in a set. Source code in `desdeo/tools/scenarios.py` ``` def _to_hashable(value: Any) -> Any: """Recursively convert a (possibly nested) list into a tuple so it can go in a set.""" if isinstance(value, list): return tuple(_to_hashable(v) for v in value) return value ``` ### append_aggregated_elem ``` append_aggregated_elem( found_type: str, new_objectives: list, new_scal_funcs: list, new_extra_funcs: list, *, name: str, symbol: str, func: Any, description: str | None = None, maximize: bool = False, is_linear: bool = False, is_convex: bool = False, is_twice_differentiable: bool = False, ) -> None ``` Append a new aggregated element to the appropriate list based on found_type. Appends an Objective if found_type is 'objectives', a ScalarizationFunction if 'scalarization_funcs', and an ExtraFunction for everything else. `description` and `maximize` are only used for objectives. Source code in `desdeo/tools/scenarios.py` ``` def append_aggregated_elem( found_type: str, new_objectives: list, new_scal_funcs: list, new_extra_funcs: list, *, name: str, symbol: str, func: Any, description: "str | None" = None, maximize: bool = False, is_linear: bool = False, is_convex: bool = False, is_twice_differentiable: bool = False, ) -> None: """Append a new aggregated element to the appropriate list based on found_type. Appends an Objective if found_type is 'objectives', a ScalarizationFunction if 'scalarization_funcs', and an ExtraFunction for everything else. ``description`` and ``maximize`` are only used for objectives. """ if found_type == "objectives": new_objectives.append( Objective( name=name, description=description, symbol=symbol, func=func, maximize=maximize, is_linear=is_linear, is_convex=is_convex, is_twice_differentiable=is_twice_differentiable, ) ) elif found_type == "scalarization_funcs": new_scal_funcs.append( ScalarizationFunction( name=name, symbol=symbol, func=func, is_linear=is_linear, is_convex=is_convex, is_twice_differentiable=is_twice_differentiable, ) ) else: new_extra_funcs.append( ExtraFunction( name=name, symbol=symbol, func=func, is_linear=is_linear, is_convex=is_convex, is_twice_differentiable=is_twice_differentiable, ) ) ``` ### build_combined_scenario_problem ``` build_combined_scenario_problem( scenario_model: ScenarioModel, ) -> tuple[Problem, dict[str, dict[str, dict[str, str]]]] ``` Build a single Problem that encodes all leaf scenarios simultaneously. Decision variables are duplicated once per leaf scenario unless a variable appears in anticipation_stop for an ancestor node, in which case all leaves under that node share one copy. Every objective, constraint, extra function, and scalarization function is also duplicated per leaf, with all variable and scenario-specific constant references rewritten to their renamed counterparts. Elements whose renamed func string is identical across all leaves that carry them are kept as a single shared element (no per-leaf prefix). Parameters: | Name | Type | Description | Default | | ---------------- | --------------- | -------------------------------------------- | ---------- | | `scenario_model` | `ScenarioModel` | the model to expand into a combined Problem. | *required* | Returns: | Type | Description | | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Problem` | A tuple of: | | `dict[str, dict[str, dict[str, str]]]` | A single Problem suitable for passing directly to a solver. | | `tuple[Problem, dict[str, dict[str, dict[str, str]]]]` | A symbol map {element_type: {original_symbol: {leaf: new_symbol}}}. Element types are "variables", "constants", "objectives", "constraints", "extra_funcs", and "scalarization_funcs". A shared element maps every leaf to the original symbol; otherwise each leaf that carries the element maps to its per-leaf copy, and leaves that do not carry it are absent from the map. | Raises: | Type | Description | | ------------ | ---------------------------------------- | | `ValueError` | if the model contains no leaf scenarios. | Source code in `desdeo/tools/scenarios.py` ``` def build_combined_scenario_problem( scenario_model: "ScenarioModel", ) -> tuple[Problem, dict[str, dict[str, dict[str, str]]]]: """Build a single Problem that encodes all leaf scenarios simultaneously. Decision variables are duplicated once per leaf scenario unless a variable appears in anticipation_stop for an ancestor node, in which case all leaves under that node share one copy. Every objective, constraint, extra function, and scalarization function is also duplicated per leaf, with all variable and scenario-specific constant references rewritten to their renamed counterparts. Elements whose renamed func string is identical across all leaves that carry them are kept as a single shared element (no per-leaf prefix). Args: scenario_model: the model to expand into a combined Problem. Returns: A tuple of: - A single Problem suitable for passing directly to a solver. - A symbol map ``{element_type: {original_symbol: {leaf: new_symbol}}}``. Element types are ``"variables"``, ``"constants"``, ``"objectives"``, ``"constraints"``, ``"extra_funcs"``, and ``"scalarization_funcs"``. A shared element maps every leaf to the original symbol; otherwise each leaf that carries the element maps to its per-leaf copy, and leaves that do not carry it are absent from the map. Raises: ValueError: if the model contains no leaf scenarios. """ leaf_scenarios: list[str] = list(scenario_model.leaf_scenarios) if not leaf_scenarios: raise ValueError("ScenarioModel has no leaf scenarios to combine.") parent_map = _build_parent_map(scenario_model.scenario_tree) scenario_problems: dict[str, Problem] = {leaf: scenario_model.get_scenario_problem(leaf) for leaf in leaf_scenarios} var_maps, combined_variables = _build_variable_maps(scenario_model, leaf_scenarios, parent_map, scenario_problems) const_maps, combined_constants = _build_constant_maps(leaf_scenarios, scenario_problems) def _name_update(elem, new_func, leaf): new_sym = elem.symbol if leaf is None else f"{leaf}_{elem.symbol}" update = {"symbol": new_sym, "func": new_func} if leaf is not None: update["name"] = f"{elem.name} ({leaf})" if isinstance(elem, Objective): update["ideal"] = None update["nadir"] = None return update def _combine(get_list, extra_maps=None): return _combine_elements( leaf_scenarios, scenario_problems, var_maps, const_maps, get_list, _name_update, extra_maps ) def _renames(symbol_map, *, with_min: bool = False) -> dict[str, dict[str, str]]: """Per-leaf renames contributed by one kind, for the kinds combined after it. Shared elements keep their original symbol and so contribute nothing. Objectives additionally contribute their ``_min`` variants, which scalarization functions and constraints may reference. """ return { leaf: { name: new_sym for orig, per_leaf in symbol_map.items() if leaf in per_leaf and per_leaf[leaf] != orig for name, new_sym in ( [(orig, per_leaf[leaf]), (f"{orig}_min", f"{per_leaf[leaf]}_min")] if with_min else [(orig, per_leaf[leaf])] ) } for leaf in leaf_scenarios } def _merge(*rename_maps) -> dict[str, dict[str, str]]: """Merge several per-leaf rename maps into one.""" return {leaf: {k: v for m in rename_maps for k, v in m[leaf].items()} for leaf in leaf_scenarios} # Kinds are combined in the order the evaluators build them: extra functions, # objectives, scalarization functions, then constraints. An element may reference the # kinds evaluated before it, so combining in the same order means those references are # already renamed by the time the referencing kind is combined. extra_funcs_list, extra_funcs_map = _combine(lambda p: p.extra_funcs) extra_renames = _renames(extra_funcs_map) objectives_list, objectives_map = _combine(lambda p: p.objectives, extra_renames) objective_renames = _merge(extra_renames, _renames(objectives_map, with_min=True)) scalarization_funcs_list, scalarization_funcs_map = _combine(lambda p: p.scalarization_funcs, objective_renames) scalarization_renames = _merge(objective_renames, _renames(scalarization_funcs_map)) constraints_list, constraints_map = _combine(lambda p: p.constraints, scalarization_renames) # Variable symbol map: original_sym -> {leaf -> new_sym}, for the leaves carrying the variable variables_map: dict[str, dict[str, str]] = { sym: {leaf: var_maps[leaf][sym] for leaf in leaf_scenarios if sym in var_maps[leaf]} for sym in dict.fromkeys(sym for leaf in leaf_scenarios for sym in var_maps[leaf]) } # Constant symbol map: original_sym -> {leaf -> new_sym}, defaulting to original all_const_syms: set[str] = {sym for lm in const_maps.values() for sym in lm} constants_map: dict[str, dict[str, str]] = { sym: {leaf: const_maps[leaf].get(sym, sym) for leaf in leaf_scenarios} for sym in all_const_syms } symbol_maps: dict[str, dict[str, dict[str, str]]] = { "variables": variables_map, "constants": constants_map, "objectives": objectives_map, "constraints": constraints_map, "extra_funcs": extra_funcs_map, "scalarization_funcs": scalarization_funcs_map, } problem = Problem( name=f"{scenario_model.base_problem.name} (combined)", description=( f"Combined scenario problem from {len(leaf_scenarios)} leaf scenarios: " + ", ".join(leaf_scenarios) ), constants=list(combined_constants.values()) or None, variables=list(combined_variables.values()), objectives=objectives_list, constraints=constraints_list, extra_funcs=extra_funcs_list, scalarization_funcs=scalarization_funcs_list, ) return problem, symbol_maps ``` ### build_scenario_problem ``` build_scenario_problem( scenario_model: ScenarioModel, scenario_name: str ) -> Problem ``` Build a concrete Problem for a single named scenario. Applies the scenario's pool overrides and additions to the base problem and returns the resulting Problem instance ready to be passed to a solver. Parameters: | Name | Type | Description | Default | | ---------------- | --------------- | -------------------------------------------------------- | ---------- | | `scenario_model` | `ScenarioModel` | the ScenarioModel containing the base problem and pools. | *required* | | `scenario_name` | `str` | the key identifying which scenario to construct. | *required* | Returns: | Type | Description | | --------- | -------------------------------------------------------- | | `Problem` | A Problem instance with the scenario's elements applied. | Raises: | Type | Description | | ------------ | ------------------------------------------- | | `ValueError` | if scenario_name is not found in the model. | Source code in `desdeo/tools/scenarios.py` ``` def build_scenario_problem(scenario_model: "ScenarioModel", scenario_name: str) -> Problem: """Build a concrete Problem for a single named scenario. Applies the scenario's pool overrides and additions to the base problem and returns the resulting Problem instance ready to be passed to a solver. Args: scenario_model: the ScenarioModel containing the base problem and pools. scenario_name: the key identifying which scenario to construct. Returns: A Problem instance with the scenario's elements applied. Raises: ValueError: if scenario_name is not found in the model. """ return scenario_model.get_scenario_problem(scenario_name) ``` ### build_scenario_symbol_maps ``` build_scenario_symbol_maps( problem: Problem, scenario_model: ScenarioModel ) -> dict[str, dict[str, dict[str, str]]] ``` Derive element symbol maps from an already-built combined scenario problem. A lightweight alternative to calling `build_combined_scenario_problem` when the combined problem is already available. The element symbols are collected from the per-leaf scenario problems, so an element a scenario introduces without the base problem declaring it is covered; the per-leaf symbol is then inferred by checking whether `{leaf}_{orig}` exists among the combined problem's element symbols. For the keys it covers, the result equals the same-named keys returned by `build_combined_scenario_problem`, and `tests/test_scenarios.py` asserts that. Covers `objectives`, `extra_funcs`, `constraints`, and `scalarization_funcs`; variables and constants are excluded because their naming depends on `anticipation_stop` and cannot be inferred from symbol presence alone. Only leaf scenarios are consulted, matching `build_combined_scenario_problem`, which builds the combined problem from the leaves alone. Elements assigned to interior tree nodes do not reach the combined problem and are therefore absent here too. Parameters: | Name | Type | Description | Default | | ---------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | the combined scenario problem (as returned by build_combined_scenario_problem or after appending aggregation elements). | *required* | | `scenario_model` | `ScenarioModel` | the scenario model used to build problem. | *required* | Returns: | Type | Description | | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dict[str, dict[str, dict[str, str]]]` | Symbol maps dict with keys "objectives", "extra_funcs", "constraints", and "scalarization_funcs", compatible with the same-named keys from build_combined_scenario_problem. | Source code in `desdeo/tools/scenarios.py` ``` def build_scenario_symbol_maps( problem: "Problem", scenario_model: "ScenarioModel", ) -> "dict[str, dict[str, dict[str, str]]]": """Derive element symbol maps from an already-built combined scenario problem. A lightweight alternative to calling `build_combined_scenario_problem` when the combined problem is already available. The element symbols are collected from the per-leaf scenario problems, so an element a scenario introduces without the base problem declaring it is covered; the per-leaf symbol is then inferred by checking whether ``{leaf}_{orig}`` exists among the combined problem's element symbols. For the keys it covers, the result equals the same-named keys returned by `build_combined_scenario_problem`, and `tests/test_scenarios.py` asserts that. Covers ``objectives``, ``extra_funcs``, ``constraints``, and ``scalarization_funcs``; variables and constants are excluded because their naming depends on ``anticipation_stop`` and cannot be inferred from symbol presence alone. Only leaf scenarios are consulted, matching `build_combined_scenario_problem`, which builds the combined problem from the leaves alone. Elements assigned to interior tree nodes do not reach the combined problem and are therefore absent here too. Args: problem: the combined scenario problem (as returned by `build_combined_scenario_problem` or after appending aggregation elements). scenario_model: the scenario model used to build ``problem``. Returns: Symbol maps dict with keys ``"objectives"``, ``"extra_funcs"``, ``"constraints"``, and ``"scalarization_funcs"``, compatible with the same-named keys from `build_combined_scenario_problem`. """ leaf_scenarios = list(scenario_model.leaf_scenarios) # The symbol universe must come from the per-leaf scenario problems, not from # base_problem: a scenario may introduce an element the base problem does not # declare, and such an element is present in the combined problem. This mirrors # `_combine_elements`, which derives its symbols the same way, so that the two # builders cannot drift apart. leaf_problems = {leaf: scenario_model.get_scenario_problem(leaf) for leaf in leaf_scenarios} def _map(get_list, combined_elems): combined_syms = {e.symbol for e in (combined_elems or [])} # Declaration order, leaf by leaf, exactly as `_combine_elements` orders them. all_syms = dict.fromkeys( elem.symbol for leaf in leaf_scenarios for elem in (get_list(leaf_problems[leaf]) or []) ) def _leaf_symbol(sym: str, leaf: str) -> "str | None": """The combined symbol for *sym* in *leaf*, or None when the leaf has none. Mirrors ``_combine_elements``: a per-leaf copy if one was made, otherwise the original symbol when the element is shared, and nothing at all when the leaf does not carry the element. """ if (prefixed := f"{leaf}_{sym}") in combined_syms: return prefixed return sym if sym in combined_syms else None return { sym: {leaf: mapped for leaf in leaf_scenarios if (mapped := _leaf_symbol(sym, leaf)) is not None} for sym in all_syms } return { "objectives": _map(lambda p: p.objectives, problem.objectives), "extra_funcs": _map(lambda p: p.extra_funcs, problem.extra_funcs), "constraints": _map(lambda p: p.constraints, problem.constraints), "scalarization_funcs": _map(lambda p: p.scalarization_funcs, problem.scalarization_funcs), } ``` ### find_base_elem ``` find_base_elem(problem: Problem, sym: str) ``` Return the first matching element from objectives, extra_funcs, scalarization_funcs, or constraints. Source code in `desdeo/tools/scenarios.py` ``` def find_base_elem(problem: "Problem", sym: str): """Return the first matching element from objectives, extra_funcs, scalarization_funcs, or constraints.""" for elems in [problem.objectives, problem.extra_funcs, problem.scalarization_funcs, problem.constraints]: elem = next((e for e in (elems or []) if e.symbol == sym), None) if elem is not None: return elem return None ``` ### leaf_expr ``` leaf_expr(info: _ElemResolution, leaf: str) -> str | list ``` Return the expression standing for the per-leaf copy of a resolved element. Usually this is the per-leaf element's symbol. Evaluators resolve a reference to an element of an earlier kind, or to an earlier element of the same kind, so an aggregate appended after the per-leaf elements it aggregates can simply name them. The exception is aggregating a **constraint**. `append_aggregated_elem` turns anything that is not an objective or a scalarization function into an extra function, and extra functions are evaluated before constraints, so the reference would point forwards and never resolve. There the per-leaf `func` is inlined instead. Parameters: | Name | Type | Description | Default | | ------ | ----------------- | ----------------------------------------------- | ---------- | | `info` | `_ElemResolution` | the resolution returned by resolve_elem. | *required* | | `leaf` | `str` | name of the leaf scenario whose copy is wanted. | *required* | Returns: | Type | Description | | ----- | ----------- | | \`str | list\` | | \`str | list\` | Source code in `desdeo/tools/scenarios.py` ``` def leaf_expr(info: _ElemResolution, leaf: str) -> "str | list": """Return the expression standing for the per-leaf copy of a resolved element. Usually this is the per-leaf element's symbol. Evaluators resolve a reference to an element of an earlier kind, or to an earlier element of the same kind, so an aggregate appended after the per-leaf elements it aggregates can simply name them. The exception is aggregating a **constraint**. ``append_aggregated_elem`` turns anything that is not an objective or a scalarization function into an extra function, and extra functions are evaluated before constraints, so the reference would point forwards and never resolve. There the per-leaf ``func`` is inlined instead. Args: info: the resolution returned by ``resolve_elem``. leaf: name of the leaf scenario whose copy is wanted. Returns: The per-leaf element's symbol, or its inlined ``func`` when a reference could not be resolved where the aggregate lands. """ leaf_sym = info.per_leaf[leaf] # Objectives and scalarization functions keep their kind; everything else aggregates # into an extra function. Variables and constants have no func and no ordering. aggregate_kind = info.found_type if info.found_type in ("objectives", "scalarization_funcs") else "extra_funcs" if _KIND_ORDER.get(info.found_type, -1) <= _KIND_ORDER[aggregate_kind]: return leaf_sym return next((e.func for e in info.elem_list if e.symbol == leaf_sym), leaf_sym) ``` ### require_all_leaves ``` require_all_leaves( sym: str, per_leaf: dict[str, str], scenario_model: ScenarioModel, ) -> None ``` Check that a symbol is defined in every leaf scenario. Aggregating an element across scenarios only means something when every scenario defines it. An element that only some scenarios carry has no value in the others, so a weighted sum, worst case or CVaR over all of them is not defined -- the result would silently be an aggregate over a subset. Shared elements pass: they map every leaf to the original symbol, which is exactly the "one value for all scenarios" case. Parameters: | Name | Type | Description | Default | | ---------------- | ---------------- | --------------------------------------------- | ---------- | | `sym` | `str` | the original symbol being aggregated. | *required* | | `per_leaf` | `dict[str, str]` | the symbol's {leaf -> combined symbol} map. | *required* | | `scenario_model` | `ScenarioModel` | the model whose leaves the symbol must cover. | *required* | Raises: | Type | Description | | ------------ | ------------------------------------------------ | | `ValueError` | if any leaf scenario does not define the symbol. | Source code in `desdeo/tools/scenarios.py` ``` def require_all_leaves( sym: str, per_leaf: "dict[str, str]", scenario_model: "ScenarioModel", ) -> None: """Check that a symbol is defined in every leaf scenario. Aggregating an element across scenarios only means something when every scenario defines it. An element that only some scenarios carry has no value in the others, so a weighted sum, worst case or CVaR over all of them is not defined -- the result would silently be an aggregate over a subset. Shared elements pass: they map every leaf to the original symbol, which is exactly the "one value for all scenarios" case. Args: sym: the original symbol being aggregated. per_leaf: the symbol's {leaf -> combined symbol} map. scenario_model: the model whose leaves the symbol must cover. Raises: ValueError: if any leaf scenario does not define the symbol. """ missing = [leaf for leaf in scenario_model.leaf_scenarios if leaf not in per_leaf] if not missing: return defined_in = sorted(per_leaf) or ["no scenario"] msg = ( f"Symbol '{sym}' is defined only in {', '.join(defined_in)}, so it cannot be aggregated " f"across all scenarios; it is missing from {', '.join(sorted(missing))}. " "Aggregate a symbol that every scenario defines, or reference this one inside its own " "scenario instead." ) raise ValueError(msg) ``` ### require_no_forward_references ``` require_no_forward_references( info: _ElemResolution, combined: Problem ) -> None ``` Check that inlining an element does not drag a forward reference along with it. An aggregate that is not an objective or a scalarization function becomes an extra function, and extra functions are evaluated first. When such an aggregate inlines a constraint (see :func:`leaf_expr`), the constraint's own expression comes with it -- and a constraint may legitimately reference an objective, which the aggregate cannot. Parameters: | Name | Type | Description | Default | | ---------- | ----------------- | ---------------------------------------------------- | ---------- | | `info` | `_ElemResolution` | the resolution returned by resolve_elem. | *required* | | `combined` | `Problem` | the combined problem the aggregate will be added to. | *required* | Raises: | Type | Description | | ------------ | ----------------------------------------------------------------------------------------------- | | `ValueError` | if an inlined expression references an element of a kind that is evaluated after the aggregate. | Source code in `desdeo/tools/scenarios.py` ``` def require_no_forward_references(info: _ElemResolution, combined: "Problem") -> None: """Check that inlining an element does not drag a forward reference along with it. An aggregate that is not an objective or a scalarization function becomes an extra function, and extra functions are evaluated first. When such an aggregate inlines a constraint (see :func:`leaf_expr`), the constraint's own expression comes with it -- and a constraint may legitimately reference an objective, which the aggregate cannot. Args: info: the resolution returned by ``resolve_elem``. combined: the combined problem the aggregate will be added to. Raises: ValueError: if an inlined expression references an element of a kind that is evaluated after the aggregate. """ aggregate_kind = info.found_type if info.found_type in ("objectives", "scalarization_funcs") else "extra_funcs" if _KIND_ORDER.get(info.found_type, -1) <= _KIND_ORDER[aggregate_kind]: # Referenced by symbol rather than inlined, so nothing is dragged along. return later_kinds = { kind: {elem.symbol for elem in (getattr(combined, kind) or [])} for kind in _KIND_ORDER if _KIND_ORDER[kind] > _KIND_ORDER[aggregate_kind] } for leaf_sym in info.per_leaf.values(): func = next((e.func for e in info.elem_list if e.symbol == leaf_sym), None) if func is None: continue used = _symbols_in(func) for symbols in later_kinds.values(): if referenced := sorted(used & symbols): msg = ( f"Cannot aggregate '{leaf_sym}': it references {', '.join(referenced)}, which are " f"evaluated after the {_KIND_NAMES[aggregate_kind]} the aggregate becomes. Define the " "quantity as an extra function and reference that instead." ) raise ValueError(msg) ``` ### resolve_elem ``` resolve_elem( sym: str, symbol_maps: dict[str, dict[str, dict[str, str]]], combined: Problem, scenario_model: ScenarioModel, ) -> _ElemResolution ``` Resolve per-symbol metadata needed by aggregation functions. Looks up the element type and per-leaf symbol map, retrieves the reference element from the combined problem for technical properties, and the original element from the base problem for name and description. Raises: | Type | Description | | ------------ | ------------------------------------------------------------------------------------------------------------ | | `ValueError` | if sym is not found in symbol_maps, or is not defined in every leaf scenario (see :func:require_all_leaves). | Source code in `desdeo/tools/scenarios.py` ``` def resolve_elem( sym: str, symbol_maps: "dict[str, dict[str, dict[str, str]]]", combined: "Problem", scenario_model: "ScenarioModel", ) -> _ElemResolution: """Resolve per-symbol metadata needed by aggregation functions. Looks up the element type and per-leaf symbol map, retrieves the reference element from the combined problem for technical properties, and the original element from the base problem for name and description. Raises: ValueError: if sym is not found in symbol_maps, or is not defined in every leaf scenario (see :func:`require_all_leaves`). """ found_type = None per_leaf = None for elem_type, smap in symbol_maps.items(): if sym in smap: found_type = elem_type per_leaf = smap[sym] break if per_leaf is None: raise ValueError(f"Symbol '{sym}' not found in the combined problem.") require_all_leaves(sym, per_leaf, scenario_model) elem_list = list( { "objectives": combined.objectives, "scalarization_funcs": combined.scalarization_funcs, "extra_funcs": combined.extra_funcs, "constraints": combined.constraints, }.get(found_type) or [] ) first_leaf_sym = per_leaf[next(iter(per_leaf))] ref_elem = next((e for e in elem_list if e.symbol == first_leaf_sym), None) base_elem = find_base_elem(scenario_model.base_problem, sym) return _ElemResolution( found_type=found_type, per_leaf=per_leaf, elem_list=elem_list, ref_elem=ref_elem, is_linear=getattr(ref_elem, "is_linear", False), is_convex=getattr(ref_elem, "is_convex", False), is_twice_diff=getattr(ref_elem, "is_twice_differentiable", False), maximize=getattr(ref_elem, "maximize", False), elem_name=base_elem.name if base_elem is not None else _longest_common_name(_pool_names_for(scenario_model, found_type, sym, per_leaf), sym), elem_desc=getattr(base_elem, "description", None) if base_elem is not None else None, ) ``` ### solve_all_scenarios ``` solve_all_scenarios( scenario_model: ScenarioModel, solver_callable: callable, solver_options: dict | None = None, ) -> dict[str, SolverResults] ``` Solve every leaf scenario in the model independently. Leaf scenarios are nodes in the scenario tree with no children. Parameters: | Name | Type | Description | Default | | ----------------- | --------------- | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `scenario_model` | `ScenarioModel` | the ScenarioModel to solve. | *required* | | `solver_callable` | `callable` | a callable that accepts a Problem (and optional options dict) and returns a SolverResults instance. | *required* | | `solver_options` | \`dict | None\` | optional dict of keyword arguments forwarded to solver_callable. | Returns: | Type | Description | | -------------------------- | ------------------------------------------------------------ | | `dict[str, SolverResults]` | A dict mapping each leaf scenario name to its SolverResults. | Source code in `desdeo/tools/scenarios.py` ``` def solve_all_scenarios( scenario_model: "ScenarioModel", solver_callable: callable, solver_options: dict | None = None, ) -> dict[str, "SolverResults"]: """Solve every leaf scenario in the model independently. Leaf scenarios are nodes in the scenario tree with no children. Args: scenario_model: the ScenarioModel to solve. solver_callable: a callable that accepts a Problem (and optional options dict) and returns a SolverResults instance. solver_options: optional dict of keyword arguments forwarded to solver_callable. Returns: A dict mapping each leaf scenario name to its SolverResults. """ return { name: solve_scenario(scenario_model, name, solver_callable, solver_options) for name in scenario_model.leaf_scenarios } ``` ### solve_scenario ``` solve_scenario( scenario_model: ScenarioModel, scenario_name: str, solver_callable: callable, solver_options: dict | None = None, ) -> SolverResults ``` Solve a single scenario. Constructs the scenario problem and passes it to the provided solver. Parameters: | Name | Type | Description | Default | | ----------------- | --------------- | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `scenario_model` | `ScenarioModel` | the ScenarioModel containing the base problem and pools. | *required* | | `scenario_name` | `str` | the key identifying which scenario to solve. | *required* | | `solver_callable` | `callable` | a callable that accepts a Problem (and optional options dict) and returns a SolverResults instance. | *required* | | `solver_options` | \`dict | None\` | optional dict of keyword arguments forwarded to solver_callable. | Returns: | Type | Description | | --------------- | ------------------------------ | | `SolverResults` | SolverResults from the solver. | Source code in `desdeo/tools/scenarios.py` ``` def solve_scenario( scenario_model: "ScenarioModel", scenario_name: str, solver_callable: callable, solver_options: dict | None = None, ) -> "SolverResults": """Solve a single scenario. Constructs the scenario problem and passes it to the provided solver. Args: scenario_model: the ScenarioModel containing the base problem and pools. scenario_name: the key identifying which scenario to solve. solver_callable: a callable that accepts a Problem (and optional options dict) and returns a SolverResults instance. solver_options: optional dict of keyword arguments forwarded to solver_callable. Returns: SolverResults from the solver. """ problem = build_scenario_problem(scenario_model, scenario_name) options = solver_options or {} return solver_callable(problem, **options) ``` ### weighted_sum_expr ``` weighted_sum_expr( info: _ElemResolution, weights: dict[str, float], combined: Problem, ) -> list ``` Build a weighted sum over the per-leaf copies of a resolved element. Terms are inlined through :func:`leaf_expr` and generated in the iteration order of *weights*. Parameters: | Name | Type | Description | Default | | ---------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `info` | `_ElemResolution` | the resolution returned by resolve_elem. | *required* | | `weights` | `dict[str, float]` | mapping from leaf scenario name to its weight. | *required* | | `combined` | `Problem` | the combined problem the weighted sum will be added to, used to reject inlined expressions carrying references the aggregate cannot resolve. | *required* | Returns: | Type | Description | | ------ | ------------------------------------------------ | | `list` | The weighted-sum expression, in MathJSON format. | Raises: | Type | Description | | ------------ | ---------------------------------------- | | `ValueError` | see :func:require_no_forward_references. | Source code in `desdeo/tools/scenarios.py` ``` def weighted_sum_expr(info: _ElemResolution, weights: "dict[str, float]", combined: "Problem") -> list: """Build a weighted sum over the per-leaf copies of a resolved element. Terms are inlined through :func:`leaf_expr` and generated in the iteration order of *weights*. Args: info: the resolution returned by ``resolve_elem``. weights: mapping from leaf scenario name to its weight. combined: the combined problem the weighted sum will be added to, used to reject inlined expressions carrying references the aggregate cannot resolve. Returns: The weighted-sum expression, in MathJSON format. Raises: ValueError: see :func:`require_no_forward_references`. """ require_no_forward_references(info, combined) terms = [["Multiply", weights[leaf], leaf_expr(info, leaf)] for leaf in weights] return terms[0] if len(terms) == 1 else ["Add", *terms] ``` ## Stochastic tools Tools for solving scenario-based optimization problems. ### add_conditional_value_at_risk ``` add_conditional_value_at_risk( scenario_model: ScenarioModel, symbols: list[str], alpha: float, var_prefix: str = "VAR_", cvar_prefix: str = "CVAR_", combined: Problem | None = None, symbol_maps: dict[str, dict[str, dict[str, str]]] | None = None, ) -> tuple[Problem, dict[str, str]] ``` Add CVaR aggregations using the Rockafellar-Uryasev LP formulation. For each symbol in `symbols`, introduces: - `{var_prefix}{sym}`: VaR threshold variable η (shared across scenarios). - `{leaf}_{var_prefix}{sym}`: per-leaf auxiliary z_s ≥ 0 such that z_s >= sym_s - eta. - `{leaf}_{var_prefix}{sym}_con`: per-leaf LTE constraint sym_s - eta - z_s \<= 0. - `{cvar_prefix}{sym}`: CVaR = eta + 1/(1-alpha) * sum_s p_s * z_s. For maximized objectives the bad tail is the low values, so the constraints are eta - sym_s - z_s \<= 0 and CVaR = eta - 1/(1-alpha) * sum_s p_s * z_s, which stays maximized. Non-objective elements always use the minimization form. The CVaR element preserves the type of the original element (objective stays objective, scalarization function stays scalarization function, anything else becomes an extra function). Parameters: | Name | Type | Description | Default | | ---------------- | ------------------------------------------ | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `scenario_model` | `ScenarioModel` | the ScenarioModel used to build or match combined. | *required* | | `symbols` | `list[str]` | original symbols whose CVaR should be added. | *required* | | `alpha` | `float` | confidence level, 0 < alpha < 1 (e.g., 0.95 for 95% CVaR). | *required* | | `var_prefix` | `str` | prefix for the VaR threshold and auxiliary variables. Defaults to 'VAR\_'. | `'VAR_'` | | `cvar_prefix` | `str` | prefix for the resulting CVaR element. Defaults to 'CVAR\_'. | `'CVAR_'` | | `combined` | \`Problem | None\` | pre-built combined Problem. If provided together with symbol_maps, build_combined_scenario_problem is not called. | | `symbol_maps` | \`dict\[str, dict\[str, dict[str, str]\]\] | None\` | pre-built symbol maps; required together with combined. | Returns: | Type | Description | | -------------------------------- | --------------------------------------------------------------------------------------------------- | | `tuple[Problem, dict[str, str]]` | A tuple of the updated combined Problem and a dict mapping each original symbol to its CVaR symbol. | Raises: | Type | Description | | ------------ | ----------------------------------------------------------- | | `ValueError` | if a requested symbol is not found in the combined problem. | Source code in `desdeo/tools/stochastic.py` ``` def add_conditional_value_at_risk( scenario_model: "ScenarioModel", symbols: list[str], alpha: float, var_prefix: str = "VAR_", cvar_prefix: str = "CVAR_", combined: "Problem | None" = None, symbol_maps: "dict[str, dict[str, dict[str, str]]] | None" = None, ) -> "tuple[Problem, dict[str, str]]": """Add CVaR aggregations using the Rockafellar-Uryasev LP formulation. For each symbol in ``symbols``, introduces: - ``{var_prefix}{sym}``: VaR threshold variable η (shared across scenarios). - ``{leaf}_{var_prefix}{sym}``: per-leaf auxiliary z_s ≥ 0 such that z_s >= sym_s - eta. - ``{leaf}_{var_prefix}{sym}_con``: per-leaf LTE constraint sym_s - eta - z_s <= 0. - ``{cvar_prefix}{sym}``: CVaR = eta + 1/(1-alpha) * sum_s p_s * z_s. For maximized objectives the bad tail is the low values, so the constraints are eta - sym_s - z_s <= 0 and CVaR = eta - 1/(1-alpha) * sum_s p_s * z_s, which stays maximized. Non-objective elements always use the minimization form. The CVaR element preserves the type of the original element (objective stays objective, scalarization function stays scalarization function, anything else becomes an extra function). Args: scenario_model: the ScenarioModel used to build or match ``combined``. symbols: original symbols whose CVaR should be added. alpha: confidence level, 0 < alpha < 1 (e.g., 0.95 for 95% CVaR). var_prefix: prefix for the VaR threshold and auxiliary variables. Defaults to ``'VAR_'``. cvar_prefix: prefix for the resulting CVaR element. Defaults to ``'CVAR_'``. combined: pre-built combined Problem. If provided together with ``symbol_maps``, ``build_combined_scenario_problem`` is not called. symbol_maps: pre-built symbol maps; required together with ``combined``. Returns: A tuple of the updated combined Problem and a dict mapping each original symbol to its CVaR symbol. Raises: ValueError: if a requested symbol is not found in the combined problem. """ if combined is None or symbol_maps is None: combined, symbol_maps = build_combined_scenario_problem(scenario_model) weights = scenario_model.leaf_scenarios scale = 1.0 / (1.0 - alpha) new_variables = list(combined.variables) new_objectives = list(combined.objectives or []) new_scal_funcs = list(combined.scalarization_funcs or []) new_extra_funcs = list(combined.extra_funcs or []) new_constraints = list(combined.constraints or []) added_symbols: dict[str, str] = {} for sym in symbols: info = resolve_elem(sym, symbol_maps, combined, scenario_model) var_sym = f"{var_prefix}{sym}" cvar_sym = f"{cvar_prefix}{sym}" added_symbols[sym] = cvar_sym is_maximize = info.found_type == "objectives" and info.maximize # VaR threshold η — shared across all scenarios. new_variables.append( Variable( name=f"VaR threshold for {info.elem_name}", symbol=var_sym, variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=0.0, ) ) # Per-leaf auxiliary variables z_s and their constraints. leaf_z_syms: dict[str, str] = {} for leaf in info.per_leaf: z_sym = f"{leaf}_{var_sym}" leaf_z_syms[leaf] = z_sym new_variables.append( Variable( name=f"CVaR auxiliary for {info.elem_name} in {leaf}", symbol=z_sym, variable_type=VariableTypeEnum.real, lowerbound=0.0, upperbound=None, initial_value=0.0, ) ) # Minimize: z_s >= sym_s - eta; maximize: z_s >= eta - sym_s leaf_func = leaf_expr(info, leaf) con_func = ( ["Add", var_sym, ["Negate", leaf_func], ["Negate", z_sym]] if is_maximize else ["Add", leaf_func, ["Negate", var_sym], ["Negate", z_sym]] ) new_constraints.append( Constraint( name=f"CVaR constraint for {info.elem_name} in {leaf}", symbol=f"{z_sym}_con", func=con_func, cons_type=ConstraintTypeEnum.LTE, is_linear=info.is_linear, is_convex=info.is_convex, is_twice_differentiable=info.is_twice_diff, ) ) # CVaR = η ± scale · Σ_s p_s · z_s (minus for maximized objectives) weighted_z = [["Multiply", weights[leaf], leaf_z_syms[leaf]] for leaf in weights] sum_z = weighted_z[0] if len(weighted_z) == 1 else ["Add", *weighted_z] append_aggregated_elem( info.found_type, new_objectives, new_scal_funcs, new_extra_funcs, name=f"CVaR of {info.elem_name}", description=f"CVaR of {info.elem_desc}" if info.elem_desc else f"CVaR of {info.elem_name}", symbol=cvar_sym, func=["Add", var_sym, ["Multiply", -scale if is_maximize else scale, sum_z]], maximize=is_maximize, is_linear=True, is_convex=True, is_twice_differentiable=True, ) return combined.model_copy( update={ "variables": new_variables, "objectives": new_objectives or None, "scalarization_funcs": new_scal_funcs or None, "extra_funcs": new_extra_funcs or None, "constraints": new_constraints or None, } ), added_symbols ``` ### add_expected_asf ``` add_expected_asf( scenario_model: ScenarioModel, symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-06, delta: float = 1e-06, ) -> tuple[Problem, str] ``` Build a combined scenario problem with an expected value of ASF scalarization. This is here mostly as a convenience for testing, but it can also be used as a template for users who want to build their own scenario problems expected-value scalarizations. Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ----------------------------------------------------------- | ----------------------------------------------------------------------------- | | `scenario_model` | `ScenarioModel` | the ScenarioModel to expand and scalarize. | *required* | | `symbol` | `str` | symbol for the scalarization function added to the problem. | *required* | | `reference_point` | `dict[str, float]` | maps objective symbols to reference point values. | *required* | | `ideal` | \`dict[str, float] | None\` | maps objective symbols to ideal values. If None, the problem's ideal is used. | | `nadir` | \`dict[str, float] | None\` | maps objective symbols to nadir values. If None, the problem's nadir is used. | | `rho` | `float` | augmentation term weight for the ASF. | `1e-06` | | `delta` | `float` | small perturbation for the differentiable ASF variant. | `1e-06` | Returns: | Type | Description | | --------------------- | ---------------------------------------------------------------------- | | `tuple[Problem, str]` | A tuple of the combined Problem and the scalarization function symbol. | Source code in `desdeo/tools/stochastic.py` ``` def add_expected_asf( scenario_model: "ScenarioModel", symbol: str, reference_point: dict[str, float], ideal: dict[str, float] | None = None, nadir: dict[str, float] | None = None, rho: float = 1e-6, delta: float = 1e-6, ) -> "tuple[Problem, str]": """Build a combined scenario problem with an expected value of ASF scalarization. This is here mostly as a convenience for testing, but it can also be used as a template for users who want to build their own scenario problems expected-value scalarizations. Args: scenario_model: the ScenarioModel to expand and scalarize. symbol: symbol for the scalarization function added to the problem. reference_point: maps objective symbols to reference point values. ideal: maps objective symbols to ideal values. If None, the problem's ideal is used. nadir: maps objective symbols to nadir values. If None, the problem's nadir is used. rho: augmentation term weight for the ASF. delta: small perturbation for the differentiable ASF variant. Returns: A tuple of the combined Problem and the scalarization function symbol. """ base_problem = scenario_model.base_problem if base_problem.is_twice_differentiable or base_problem.is_linear: scal_problem, scal = add_asf_diff( problem=base_problem, symbol=symbol, reference_point=reference_point, ideal=ideal, nadir=nadir, rho=rho, delta=delta, ) else: scal_problem, scal = add_asf_nondiff( problem=base_problem, symbol=symbol, reference_point=reference_point, ideal=ideal, nadir=nadir, rho=rho, delta=delta, ) modified_model = scenario_model.with_base_problem(problem=scal_problem, validate=True) combined, symbol_maps = build_combined_scenario_problem(modified_model) combined, added = add_expected_value(modified_model, [scal], combined=combined, symbol_maps=symbol_maps) return combined, added[scal] ``` ### add_expected_value ``` add_expected_value( scenario_model: ScenarioModel, symbols: list[str], prefix: str = "E_", combined: Problem | None = None, symbol_maps: dict[str, dict[str, dict[str, str]]] | None = None, ) -> tuple[Problem, dict[str, str]] ``` Add expected-value aggregations for selected symbols to the combined scenario problem. For each symbol the expected value is a probability-weighted sum of the per-leaf copies of that symbol in the combined problem. The new element type matches the original: objectives stay objectives, scalarization functions stay scalarization functions, and everything else (extra functions, constraints, …) becomes an extra function. Parameters: | Name | Type | Description | Default | | ---------------- | ------------------------------------------ | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `scenario_model` | `ScenarioModel` | the ScenarioModel to expand. | *required* | | `symbols` | `list[str]` | original symbols whose expected values should be added. | *required* | | `prefix` | `str` | prefix prepended to each original symbol to form the new symbol. Defaults to 'E\_'. | `'E_'` | | `combined` | \`Problem | None\` | pre-built combined Problem. If provided together with symbol_maps, build_combined_scenario_problem is not called. Must match scenario_model. | | `symbol_maps` | \`dict\[str, dict\[str, dict[str, str]\]\] | None\` | pre-built symbol maps from build_combined_scenario_problem. Must be provided together with combined; ignored otherwise. | Returns: | Type | Description | | ---------------- | -------------------------------------------------------------------------- | | `Problem` | A tuple of the combined Problem with the expected-value elements appended, | | `dict[str, str]` | and a dict mapping each original symbol to its new expected-value symbol. | Raises: | Type | Description | | ------------ | ----------------------------------------------------------- | | `ValueError` | if a requested symbol is not found in the combined problem. | Source code in `desdeo/tools/stochastic.py` ``` def add_expected_value( scenario_model: "ScenarioModel", symbols: list[str], prefix: str = "E_", combined: "Problem | None" = None, symbol_maps: "dict[str, dict[str, dict[str, str]]] | None" = None, ) -> "tuple[Problem, dict[str, str]]": """Add expected-value aggregations for selected symbols to the combined scenario problem. For each symbol the expected value is a probability-weighted sum of the per-leaf copies of that symbol in the combined problem. The new element type matches the original: objectives stay objectives, scalarization functions stay scalarization functions, and everything else (extra functions, constraints, …) becomes an extra function. Args: scenario_model: the ScenarioModel to expand. symbols: original symbols whose expected values should be added. prefix: prefix prepended to each original symbol to form the new symbol. Defaults to ``'E_'``. combined: pre-built combined Problem. If provided together with ``symbol_maps``, ``build_combined_scenario_problem`` is not called. Must match ``scenario_model``. symbol_maps: pre-built symbol maps from ``build_combined_scenario_problem``. Must be provided together with ``combined``; ignored otherwise. Returns: A tuple of the combined Problem with the expected-value elements appended, and a dict mapping each original symbol to its new expected-value symbol. Raises: ValueError: if a requested symbol is not found in the combined problem. """ if combined is None or symbol_maps is None: combined, symbol_maps = build_combined_scenario_problem(scenario_model) weights = scenario_model.leaf_scenarios new_objectives = list(combined.objectives or []) new_scal_funcs = list(combined.scalarization_funcs or []) new_extra_funcs = list(combined.extra_funcs or []) added_symbols: dict[str, str] = {} for sym in symbols: info = resolve_elem(sym, symbol_maps, combined, scenario_model) expected_sym = f"{prefix}{sym}" added_symbols[sym] = expected_sym expected_expr = weighted_sum_expr(info, weights, combined) append_aggregated_elem( info.found_type, new_objectives, new_scal_funcs, new_extra_funcs, name=f"Expected {info.elem_name}", description=f"Expected value of {info.elem_desc}" if info.elem_desc else f"Expected value of {info.elem_name}", symbol=expected_sym, func=expected_expr, maximize=info.maximize, is_linear=info.is_linear, is_convex=info.is_convex, is_twice_differentiable=info.is_twice_diff, ) return combined.model_copy( update={ "objectives": new_objectives or None, "scalarization_funcs": new_scal_funcs or None, "extra_funcs": new_extra_funcs or None, } ), added_symbols ``` ## Robust tools Tools for worst-case robust optimization over scenario-based problems. ### add_single_objective_worst_case_regret ``` add_single_objective_worst_case_regret( scenario_model: ScenarioModel, symbols: list[str], ideals: dict[str, dict[str, float]], prefix: str = "regret_wc_", combined: Problem | None = None, symbol_maps: dict[str, dict[str, dict[str, str]]] | None = None, ) -> tuple[Problem, dict[str, str]] ``` Add worst-case regret aggregations for selected symbols to the combined scenario problem. For each symbol, the per-scenario regret is the difference between the objective value in that scenario and its ideal (best achievable) value in that scenario: - **Minimise** objectives: `regret_s = f_s - ideal_s` (ideal is the minimum). - **Maximise** objectives: `regret_s = ideal_s - f_s` (ideal is the maximum). The worst-case regret across all scenarios is then expressed via the standard epigraph reformulation: minimise `t` subject to `regret_s - t <= 0` for every leaf scenario `s`. The resulting element is always a **minimise** objective (or extra function / scalarization function matching the original type) regardless of the original optimisation direction. Parameters: | Name | Type | Description | Default | | ---------------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `scenario_model` | `ScenarioModel` | the ScenarioModel to expand. | *required* | | `symbols` | `list[str]` | original symbols whose worst-case regret should be added. | *required* | | `ideals` | `dict[str, dict[str, float]]` | mapping {symbol -> {leaf -> ideal_value}} giving the ideal (best achievable) value of each symbol in each leaf scenario. Every leaf returned by scenario_model.leaf_scenarios must have an entry for each symbol. | *required* | | `prefix` | `str` | prefix prepended to each original symbol to form the new symbol. Defaults to 'regret_wc\_'. | `'regret_wc_'` | | `combined` | \`Problem | None\` | pre-built combined Problem. If provided together with symbol_maps, build_combined_scenario_problem is not called. Must match scenario_model. | | `symbol_maps` | \`dict\[str, dict\[str, dict[str, str]\]\] | None\` | pre-built symbol maps from build_combined_scenario_problem. Must be provided together with combined; ignored otherwise. | Returns: | Type | Description | | ---------------- | ------------------------------------------------------------------------- | | `Problem` | A tuple of the combined Problem with worst-case regret elements appended, | | `dict[str, str]` | and a dict mapping each original symbol to its regret symbol. | Raises: | Type | Description | | ------------ | ----------------------------------------------------------- | | `ValueError` | if a requested symbol is not found in the combined problem. | | `ValueError` | if ideals is missing a leaf entry for any requested symbol. | Source code in `desdeo/tools/robust.py` ``` def add_single_objective_worst_case_regret( scenario_model: "ScenarioModel", symbols: list[str], ideals: "dict[str, dict[str, float]]", prefix: str = "regret_wc_", combined: "Problem | None" = None, symbol_maps: "dict[str, dict[str, dict[str, str]]] | None" = None, ) -> "tuple[Problem, dict[str, str]]": """Add worst-case regret aggregations for selected symbols to the combined scenario problem. For each symbol, the per-scenario regret is the difference between the objective value in that scenario and its ideal (best achievable) value in that scenario: * **Minimise** objectives: ``regret_s = f_s - ideal_s`` (ideal is the minimum). * **Maximise** objectives: ``regret_s = ideal_s - f_s`` (ideal is the maximum). The worst-case regret across all scenarios is then expressed via the standard epigraph reformulation: minimise ``t`` subject to ``regret_s - t <= 0`` for every leaf scenario ``s``. The resulting element is always a **minimise** objective (or extra function / scalarization function matching the original type) regardless of the original optimisation direction. Args: scenario_model: the ScenarioModel to expand. symbols: original symbols whose worst-case regret should be added. ideals: mapping ``{symbol -> {leaf -> ideal_value}}`` giving the ideal (best achievable) value of each symbol in each leaf scenario. Every leaf returned by ``scenario_model.leaf_scenarios`` must have an entry for each symbol. prefix: prefix prepended to each original symbol to form the new symbol. Defaults to ``'regret_wc_'``. combined: pre-built combined Problem. If provided together with ``symbol_maps``, ``build_combined_scenario_problem`` is not called. Must match ``scenario_model``. symbol_maps: pre-built symbol maps from ``build_combined_scenario_problem``. Must be provided together with ``combined``; ignored otherwise. Returns: A tuple of the combined Problem with worst-case regret elements appended, and a dict mapping each original symbol to its regret symbol. Raises: ValueError: if a requested symbol is not found in the combined problem. ValueError: if ``ideals`` is missing a leaf entry for any requested symbol. """ if combined is None or symbol_maps is None: combined, symbol_maps = build_combined_scenario_problem(scenario_model) new_variables = list(combined.variables) new_objectives = list(combined.objectives or []) new_scal_funcs = list(combined.scalarization_funcs or []) new_extra_funcs = list(combined.extra_funcs or []) new_constraints = list(combined.constraints or []) added_symbols: dict[str, str] = {} for sym in symbols: info = resolve_elem(sym, symbol_maps, combined, scenario_model) regret_sym = f"{prefix}{sym}" t_sym = f"_t_{regret_sym}" added_symbols[sym] = regret_sym sym_ideals = ideals.get(sym, {}) missing_leaves = set(info.per_leaf) - set(sym_ideals) if missing_leaves: raise ValueError(f"ideals is missing entries for symbol '{sym}' in leaves: {missing_leaves}") new_variables.append( Variable( name=f"Worst-case regret epigraph variable for {info.elem_name}", symbol=t_sym, variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=0.0, ) ) for leaf, leaf_sym in info.per_leaf.items(): ideal_val = sym_ideals[leaf] # Minimise: regret_s = f_s - ideal_s -> f_s - ideal_s - t <= 0 # Maximise: regret_s = ideal_s - f_s -> ideal_s - f_s - t <= 0 if info.maximize: con_func = ["Add", ideal_val, ["Negate", leaf_sym], ["Negate", t_sym]] else: con_func = ["Add", leaf_sym, -ideal_val, ["Negate", t_sym]] new_constraints.append( Constraint( name=f"Worst-case regret bound for {info.elem_name} in {leaf}", symbol=f"{leaf}_{regret_sym}_con", func=con_func, cons_type=ConstraintTypeEnum.LTE, is_linear=info.is_linear, is_convex=info.is_convex, is_twice_differentiable=info.is_twice_diff, ) ) append_aggregated_elem( info.found_type, new_objectives, new_scal_funcs, new_extra_funcs, name=f"Worst-case regret {info.elem_name}", description=f"Worst-case regret of {info.elem_desc}" if info.elem_desc else f"Worst-case regret of {info.elem_name}", symbol=regret_sym, func=t_sym, maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ) return combined.model_copy( update={ "variables": new_variables, "objectives": new_objectives or None, "scalarization_funcs": new_scal_funcs or None, "extra_funcs": new_extra_funcs or None, "constraints": new_constraints or None, } ), added_symbols ``` ### add_weighted_scenarios ``` add_weighted_scenarios( scenario_model: ScenarioModel, symbols: list[str], weights: dict[str, float], prefix: str = "weighted_", combined: Problem | None = None, symbol_maps: dict[str, dict[str, dict[str, str]]] | None = None, ) -> tuple[Problem, dict[str, str]] ``` Add user-weighted aggregations for selected symbols to the combined scenario problem. Identical to `add_expected_value` in `desdeo.tools.stochastic`, except that the per-leaf weights come from the caller rather than from the scenario probabilities in `scenario_model`. This lets you express, e.g., pessimistic weightings that put more mass on bad scenarios than their true probabilities warrant. The new element type matches the original: objectives stay objectives, scalarization functions stay scalarization functions, and everything else becomes an extra function. Parameters: | Name | Type | Description | Default | | ---------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | `scenario_model` | `ScenarioModel` | the ScenarioModel to expand. | *required* | | `symbols` | `list[str]` | original symbols whose weighted sums should be added. | *required* | | `weights` | `dict[str, float]` | mapping from leaf scenario name to its weight. Must contain a key for every leaf in scenario_model.leaf_scenarios. | *required* | | `prefix` | `str` | prefix prepended to each original symbol to form the new symbol. Defaults to 'weighted\_'. | `'weighted_'` | | `combined` | \`Problem | None\` | pre-built combined Problem. If provided together with symbol_maps, build_combined_scenario_problem is not called. Must match scenario_model. | | `symbol_maps` | \`dict\[str, dict\[str, dict[str, str]\]\] | None\` | pre-built symbol maps from build_combined_scenario_problem. Must be provided together with combined; ignored otherwise. | Returns: | Type | Description | | ---------------- | ------------------------------------------------------------------------------- | | `Problem` | A tuple of the combined Problem with the weighted elements appended, and a dict | | `dict[str, str]` | mapping each original symbol to its new weighted symbol. | Raises: | Type | Description | | ------------ | ----------------------------------------------------------- | | `ValueError` | if a requested symbol is not found in the combined problem. | | `ValueError` | if weights is missing a key for any leaf scenario. | Source code in `desdeo/tools/robust.py` ``` def add_weighted_scenarios( scenario_model: "ScenarioModel", symbols: list[str], weights: dict[str, float], prefix: str = "weighted_", combined: "Problem | None" = None, symbol_maps: "dict[str, dict[str, dict[str, str]]] | None" = None, ) -> "tuple[Problem, dict[str, str]]": """Add user-weighted aggregations for selected symbols to the combined scenario problem. Identical to ``add_expected_value`` in ``desdeo.tools.stochastic``, except that the per-leaf weights come from the caller rather than from the scenario probabilities in ``scenario_model``. This lets you express, e.g., pessimistic weightings that put more mass on bad scenarios than their true probabilities warrant. The new element type matches the original: objectives stay objectives, scalarization functions stay scalarization functions, and everything else becomes an extra function. Args: scenario_model: the ScenarioModel to expand. symbols: original symbols whose weighted sums should be added. weights: mapping from leaf scenario name to its weight. Must contain a key for every leaf in ``scenario_model.leaf_scenarios``. prefix: prefix prepended to each original symbol to form the new symbol. Defaults to ``'weighted_'``. combined: pre-built combined Problem. If provided together with ``symbol_maps``, ``build_combined_scenario_problem`` is not called. Must match ``scenario_model``. symbol_maps: pre-built symbol maps from ``build_combined_scenario_problem``. Must be provided together with ``combined``; ignored otherwise. Returns: A tuple of the combined Problem with the weighted elements appended, and a dict mapping each original symbol to its new weighted symbol. Raises: ValueError: if a requested symbol is not found in the combined problem. ValueError: if ``weights`` is missing a key for any leaf scenario. """ if combined is None or symbol_maps is None: combined, symbol_maps = build_combined_scenario_problem(scenario_model) leaf_scenarios = scenario_model.leaf_scenarios missing = set(leaf_scenarios) - set(weights) if missing: raise ValueError(f"weights is missing keys for leaf scenarios: {missing}") new_objectives = list(combined.objectives or []) new_scal_funcs = list(combined.scalarization_funcs or []) new_extra_funcs = list(combined.extra_funcs or []) added_symbols: dict[str, str] = {} for sym in symbols: info = resolve_elem(sym, symbol_maps, combined, scenario_model) weighted_expr = weighted_sum_expr(info, {leaf: weights[leaf] for leaf in leaf_scenarios}, combined) weighted_sym = f"{prefix}{sym}" added_symbols[sym] = weighted_sym append_aggregated_elem( info.found_type, new_objectives, new_scal_funcs, new_extra_funcs, name=f"Weighted {info.elem_name}", description=f"Weighted scenario value of {info.elem_desc}" if info.elem_desc else f"Weighted scenario value of {info.elem_name}", symbol=weighted_sym, func=weighted_expr, maximize=info.maximize, is_linear=info.is_linear, is_convex=info.is_convex, is_twice_differentiable=info.is_twice_diff, ) return combined.model_copy( update={ "objectives": new_objectives or None, "scalarization_funcs": new_scal_funcs or None, "extra_funcs": new_extra_funcs or None, } ), added_symbols ``` ### add_worst_case_robust ``` add_worst_case_robust( scenario_model: ScenarioModel, symbols: list[str], prefix: str = "robust_", combined: Problem | None = None, symbol_maps: dict[str, dict[str, dict[str, str]]] | None = None, ) -> tuple[Problem, dict[str, str]] ``` Add worst-case robust aggregations for selected symbols to the combined scenario problem. Uses the standard epigraph reformulation with an auxiliary variable `t` and per-leaf bound constraints, avoiding non-smooth `Max`/`Min` expressions that most solvers cannot handle. The worst-case direction matches the original optimisation direction: - **Minimise** objectives / scalarization functions / extra functions — worst case is the largest value across scenarios. Adds constraints `f_s - t <= 0` and exposes `t` as a new **minimise** element (equivalent to `min max_s f_s`). - **Maximise** objectives — worst case is the smallest value across scenarios. Adds constraints `t - f_s <= 0` and exposes `t` as a new **maximise** element (equivalent to `max min_s f_s`). The new element type matches the original: objectives stay objectives, scalarization functions stay scalarization functions, and everything else becomes an extra function. The epigraph variable is named `_t_{prefix}{sym}` and the returned element is `{prefix}{sym}`. Parameters: | Name | Type | Description | Default | | ---------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `scenario_model` | `ScenarioModel` | the ScenarioModel to expand. | *required* | | `symbols` | `list[str]` | original symbols whose worst-case values should be added. | *required* | | `prefix` | `str` | prefix prepended to each original symbol to form the new symbol. Defaults to 'robust\_'. | `'robust_'` | | `combined` | \`Problem | None\` | pre-built combined Problem. If provided together with symbol_maps, build_combined_scenario_problem is not called. Must match scenario_model. | | `symbol_maps` | \`dict\[str, dict\[str, dict[str, str]\]\] | None\` | pre-built symbol maps from build_combined_scenario_problem. Must be provided together with combined; ignored otherwise. | Returns: | Type | Description | | ---------------- | ------------------------------------------------------------------------- | | `Problem` | A tuple of the combined Problem with robust elements appended, and a dict | | `dict[str, str]` | mapping each original symbol to its robust symbol. | Raises: | Type | Description | | ------------ | ----------------------------------------------------------- | | `ValueError` | if a requested symbol is not found in the combined problem. | Source code in `desdeo/tools/robust.py` ``` def add_worst_case_robust( scenario_model: "ScenarioModel", symbols: list[str], prefix: str = "robust_", combined: "Problem | None" = None, symbol_maps: "dict[str, dict[str, dict[str, str]]] | None" = None, ) -> "tuple[Problem, dict[str, str]]": """Add worst-case robust aggregations for selected symbols to the combined scenario problem. Uses the standard epigraph reformulation with an auxiliary variable ``t`` and per-leaf bound constraints, avoiding non-smooth ``Max``/``Min`` expressions that most solvers cannot handle. The worst-case direction matches the original optimisation direction: * **Minimise** objectives / scalarization functions / extra functions — worst case is the largest value across scenarios. Adds constraints ``f_s - t <= 0`` and exposes ``t`` as a new **minimise** element (equivalent to ``min max_s f_s``). * **Maximise** objectives — worst case is the smallest value across scenarios. Adds constraints ``t - f_s <= 0`` and exposes ``t`` as a new **maximise** element (equivalent to ``max min_s f_s``). The new element type matches the original: objectives stay objectives, scalarization functions stay scalarization functions, and everything else becomes an extra function. The epigraph variable is named ``_t_{prefix}{sym}`` and the returned element is ``{prefix}{sym}``. Args: scenario_model: the ScenarioModel to expand. symbols: original symbols whose worst-case values should be added. prefix: prefix prepended to each original symbol to form the new symbol. Defaults to ``'robust_'``. combined: pre-built combined Problem. If provided together with ``symbol_maps``, ``build_combined_scenario_problem`` is not called. Must match ``scenario_model``. symbol_maps: pre-built symbol maps from ``build_combined_scenario_problem``. Must be provided together with ``combined``; ignored otherwise. Returns: A tuple of the combined Problem with robust elements appended, and a dict mapping each original symbol to its robust symbol. Raises: ValueError: if a requested symbol is not found in the combined problem. """ if combined is None or symbol_maps is None: combined, symbol_maps = build_combined_scenario_problem(scenario_model) new_variables = list(combined.variables) new_objectives = list(combined.objectives or []) new_scal_funcs = list(combined.scalarization_funcs or []) new_extra_funcs = list(combined.extra_funcs or []) new_constraints = list(combined.constraints or []) added_symbols: dict[str, str] = {} for sym in symbols: info = resolve_elem(sym, symbol_maps, combined, scenario_model) robust_sym = f"{prefix}{sym}" t_sym = f"_t_{robust_sym}" added_symbols[sym] = robust_sym is_maximize = info.found_type == "objectives" and info.maximize # Epigraph variable t. # Minimise objective: t >= f_s for all s -> t = max_s f_s -> minimise t. # Maximise objective: t <= f_s for all s -> t = min_s f_s -> maximise t. new_variables.append( Variable( name=f"Worst-case robust epigraph variable for {info.elem_name}", symbol=t_sym, variable_type=VariableTypeEnum.real, lowerbound=None, upperbound=None, initial_value=0.0, ) ) for leaf, leaf_sym in info.per_leaf.items(): # Maximise: t - f_s <= 0 -> t <= f_s. Minimise: f_s - t <= 0 -> f_s <= t. con_func = ["Add", t_sym, ["Negate", leaf_sym]] if is_maximize else ["Add", leaf_sym, ["Negate", t_sym]] new_constraints.append( Constraint( name=f"Worst-case robust bound for {info.elem_name} in {leaf}", symbol=f"{leaf}_{robust_sym}_con", func=con_func, cons_type=ConstraintTypeEnum.LTE, is_linear=info.is_linear, is_convex=info.is_convex, is_twice_differentiable=info.is_twice_diff, ) ) append_aggregated_elem( info.found_type, new_objectives, new_scal_funcs, new_extra_funcs, name=f"Worst-case {info.elem_name}", description=f"Worst-case robust value of {info.elem_desc}" if info.elem_desc else f"Worst-case robust value of {info.elem_name}", symbol=robust_sym, func=t_sym, maximize=is_maximize, is_linear=True, is_convex=True, is_twice_differentiable=True, ) return combined.model_copy( update={ "variables": new_variables, "objectives": new_objectives or None, "scalarization_funcs": new_scal_funcs or None, "extra_funcs": new_extra_funcs or None, "constraints": new_constraints or None, } ), added_symbols ``` ## Unary indicators This module implements unary indicators that can be used to evaluate the quality of a single solution set. It assumes that the solution set has been normalized just that *some* ideal point (not necessarily the ideal point of the set) is the origin and *some* nadir point (not necessarily the nadir point of the set) is (1, 1, ..., 1). The normalized solution set is assumed to be inside the bounding box [0, 1]^k where k is the number of objectives. If these conditions are not met, the results of the indicators will not be meaningful. Additionally, the set may be assumed to only contain mutually non-dominated solutions, depending on the indicator. For now, we rely on pymoo for the implementation of some of the indicators. Find more information about the indicators in: Audet, Charles, et al. "Performance indicators in multiobjective optimization." European journal of operational research 292.2 (2021): 397-422. ### DPhiIndicators Bases: `BaseModel` A container for the desirability based hypervolume indicator D-PHI and its complementary indicator. Source code in `desdeo/tools/indicators_unary.py` ``` class DPhiIndicators(BaseModel): """A container for the desirability based hypervolume indicator D-PHI and its complementary indicator.""" d_phi: float = Field(description="The D-PHI indicator value. Higher is better.") "The D-PHI indicator value. Higher is better." ci: float = Field( description=( "The complementary indicator (CI) value, the negated achievement scalarizing function value of the " "best solution in the set with respect to the aspiration and reservation points. Higher is better, " "and the value is non-negative if and only if at least one solution reaches all aspiration levels." ) ) "The complementary indicator (CI) value. Higher is better." ``` #### ci ``` ci: float = Field( description="The complementary indicator (CI) value, the negated achievement scalarizing function value of the best solution in the set with respect to the aspiration and reservation points. Higher is better, and the value is non-negative if and only if at least one solution reaches all aspiration levels." ) ``` The complementary indicator (CI) value. Higher is better. #### d_phi ``` d_phi: float = Field( description="The D-PHI indicator value. Higher is better." ) ``` The D-PHI indicator value. Higher is better. ### DistanceIndicators Bases: `BaseModel` A container for closely related distance based indicators. Source code in `desdeo/tools/indicators_unary.py` ``` class DistanceIndicators(BaseModel): """A container for closely related distance based indicators.""" igd: float = Field(description="The inverted generational distance (IGD) indicator value.") "The inverted generational distance (IGD) indicator value." igd_p: float = Field( description=( "The IGD_p indicator, where instead of the arithmetic mean of the distances, the " "generalized (power) mean of order p is taken. Equals `igd` when p == 1." ) ) "The IGD_p indicator, where instead of the arithmetic mean of the distances, the generalized (power) mean" " of order p is taken. Equals `igd` when p == 1." gd: float = Field(description="The generational distance (GD) indicator value.") "The generational distance (GD) indicator value." gd_p: float = Field( description=( "The GD_p indicator, where instead of the arithmetic mean of the distances, the " "generalized (power) mean of order p is taken. Equals `gd` when p == 1." ) ) "The GD_p indicator, where instead of the arithmetic mean of the distances, the generalized (power) mean" " of order p is taken. Equals `gd` when p == 1." ahd: float = Field(description="The averaged Hausdorff distance (Delta_p) indicator value, max(igd_p, gd_p).") "The averaged Hausdorff distance (Delta_p) indicator value, max(igd_p, gd_p)." ``` #### ahd ``` ahd: float = Field( description="The averaged Hausdorff distance (Delta_p) indicator value, max(igd_p, gd_p)." ) ``` The averaged Hausdorff distance (Delta_p) indicator value, max(igd_p, gd_p). #### gd ``` gd: float = Field( description="The generational distance (GD) indicator value." ) ``` The generational distance (GD) indicator value. #### gd_p ``` gd_p: float = Field( description="The GD_p indicator, where instead of the arithmetic mean of the distances, the generalized (power) mean of order p is taken. Equals `gd` when p == 1." ) ``` The GD_p indicator, where instead of the arithmetic mean of the distances, the generalized (power) mean #### igd ``` igd: float = Field( description="The inverted generational distance (IGD) indicator value." ) ``` The inverted generational distance (IGD) indicator value. #### igd_p ``` igd_p: float = Field( description="The IGD_p indicator, where instead of the arithmetic mean of the distances, the generalized (power) mean of order p is taken. Equals `igd` when p == 1." ) ``` The IGD_p indicator, where instead of the arithmetic mean of the distances, the generalized (power) mean ### IGDPlusIndicators Bases: `BaseModel` A container for the IGD+ distance-based indicator. Source code in `desdeo/tools/indicators_unary.py` ``` class IGDPlusIndicators(BaseModel): """A container for the IGD+ distance-based indicator.""" igd_plus: float = Field(description="The modified inverted generational distance (IGD+) indicator value.") ``` ### PhiPlusIndicator Bases: `BaseModel` A container for the PHI+ indicator. Source code in `desdeo/tools/indicators_unary.py` ``` class PhiPlusIndicator(BaseModel): """A container for the PHI+ indicator.""" phi_plus: float = Field( description=( "The PHI+ indicator value, the share of the region of interest covered by the solution set. Higher is " "better. The value is zero if no solution falls in the region of interest, and it exceeds one when " "the set contains solutions better than the reference point." ) ) "The PHI+ indicator value. Higher is better." ``` #### phi_plus ``` phi_plus: float = Field( description="The PHI+ indicator value, the share of the region of interest covered by the solution set. Higher is better. The value is zero if no solution falls in the region of interest, and it exceeds one when the set contains solutions better than the reference point." ) ``` The PHI+ indicator value. Higher is better. ### R2Indicator Bases: `BaseModel` Container for the R2 indicator value of a solution set. Source code in `desdeo/tools/indicators_unary.py` ``` class R2Indicator(BaseModel): """Container for the R2 indicator value of a solution set.""" r2_value: float """The R2 indicator value. **Higher is better, and the value is always negative.** This is the utility form of R2, and it is the opposite orientation to every other indicator in this module. See `r2_indicator` for why, and do not put it on a chart beside IGD+ or GD without flipping its sign first.""" ``` #### r2_value ``` r2_value: float ``` The R2 indicator value. **Higher is better, and the value is always negative.** This is the utility form of R2, and it is the opposite orientation to every other indicator in this module. See `r2_indicator` for why, and do not put it on a chart beside IGD+ or GD without flipping its sign first. ### RMetricIndicators Bases: `BaseModel` A container for R-metric indicators: R-HV and R-IGD. Source code in `desdeo/tools/indicators_unary.py` ``` class RMetricIndicators(BaseModel): """A container for R-metric indicators: R-HV and R-IGD.""" r_hv: float = Field(description="The R-HV indicator value, based on hypervolume.") "The R-HV indicator value, based on hypervolume." r_igd: float = Field(description="The R-IGD indicator value, based on inverted generational distance.") "The R-IGD indicator value, based on inverted generational distance." ``` #### r_hv ``` r_hv: float = Field( description="The R-HV indicator value, based on hypervolume." ) ``` The R-HV indicator value, based on hypervolume. #### r_igd ``` r_igd: float = Field( description="The R-IGD indicator value, based on inverted generational distance." ) ``` The R-IGD indicator value, based on inverted generational distance. ### \_as_objective_vector ``` _as_objective_vector( value: float | ndarray, num_objectives: int, name: str ) -> np.ndarray ``` Broadcasts a scalar or a 1-D array into a 1-D array with one entry per objective. Parameters: | Name | Type | Description | Default | | ---------------- | ------- | ----------------------------------------------------------------- | -------------------------------------------------------------- | | `value` | \`float | ndarray\` | A scalar shared by all objectives, or one value per objective. | | `num_objectives` | `int` | The number of objectives, i.e., the length of the returned array. | *required* | | `name` | `str` | The name of the argument, used in the error message. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------- | | `ndarray` | np.ndarray: A 1-D array of length num_objectives. | Raises: | Type | Description | | ------------ | ---------------------------------------------------------- | | `ValueError` | If value is neither a scalar nor of length num_objectives. | Source code in `desdeo/tools/indicators_unary.py` ``` def _as_objective_vector(value: float | np.ndarray, num_objectives: int, name: str) -> np.ndarray: """Broadcasts a scalar or a 1-D array into a 1-D array with one entry per objective. Args: value (float | np.ndarray): A scalar shared by all objectives, or one value per objective. num_objectives (int): The number of objectives, i.e., the length of the returned array. name (str): The name of the argument, used in the error message. Returns: np.ndarray: A 1-D array of length `num_objectives`. Raises: ValueError: If `value` is neither a scalar nor of length `num_objectives`. """ array = np.atleast_1d(np.asarray(value, dtype=float)).flatten() if array.size == 1: return np.full(num_objectives, array[0]) if array.size != num_objectives: raise ValueError( f"'{name}' must be a scalar or have one value per objective ({num_objectives}), got {array.size}." ) return array ``` ### \_power_mean ``` _power_mean(distances: ndarray, p: float) -> float ``` Computes the generalized (power) mean of order p of a 1D array of non-negative distances. Parameters: | Name | Type | Description | Default | | ----------- | --------- | --------------------------------------------------------------------------------- | ---------- | | `distances` | `ndarray` | A 1D array of non-negative distances. | *required* | | `p` | `float` | The order of the mean. Must be positive. np.inf (or math.inf) yields the maximum. | *required* | Returns: | Name | Type | Description | | ------- | ------- | -------------------------------- | | `float` | `float` | The generalized mean of order p. | Source code in `desdeo/tools/indicators_unary.py` ``` def _power_mean(distances: np.ndarray, p: float) -> float: """Computes the generalized (power) mean of order p of a 1D array of non-negative distances. Args: distances (np.ndarray): A 1D array of non-negative distances. p (float): The order of the mean. Must be positive. np.inf (or math.inf) yields the maximum. Returns: float: The generalized mean of order p. """ if np.isinf(p): return float(distances.max()) return float(np.mean(distances**p) ** (1 / p)) ``` ### d_phi_batch ``` d_phi_batch( solution_sets: dict[str, ndarray], aspiration_point: float | ndarray, reservation_point: float | ndarray, *, c1: float | ndarray = 1.0, c2: float | ndarray = 0.0, epsilon_a: float | ndarray = 0.2, epsilon_r: float | ndarray = 0.2, delta: float = 0.01, ) -> dict[str, DPhiIndicators] ``` Computes the D-PHI and CI indicators for multiple solution sets. Note The minimization of the objective function values is assumed. Parameters: | Name | Type | Description | Default | | ------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `solution_sets` | `dict[str, ndarray]` | A dict of strings mapped to 2D numpy arrays where each array contains a set of solutions. The keys of the dict are the names of the sets. The sets must have the same number of objectives/columns but can have a different number of solutions/rows. | *required* | | `aspiration_point` | \`float | ndarray\` | The aspiration point, shared by all the sets. | | `reservation_point` | \`float | ndarray\` | The reservation point, shared by all the sets. | | `c1` | \`float | ndarray\` | The desirability of the aspiration levels. Defaults to 1.0. | | `c2` | \`float | ndarray\` | The desirability of the reservation levels. Defaults to 0.0. | | `epsilon_a` | \`float | ndarray\` | The upper limit parameter. Defaults to 0.2. | | `epsilon_r` | \`float | ndarray\` | The lower limit parameter. Defaults to 0.2. | | `delta` | `float` | A small positive number, see d_phi_indicator. Defaults to 1e-2. | `0.01` | Returns: | Type | Description | | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `dict[str, DPhiIndicators]` | dict\[str, DPhiIndicators\]: A dict of strings mapped to DPhiIndicators objects. The keys of the dict are the names of the sets. | Source code in `desdeo/tools/indicators_unary.py` ``` def d_phi_batch( solution_sets: dict[str, np.ndarray], aspiration_point: float | np.ndarray, reservation_point: float | np.ndarray, *, c1: float | np.ndarray = 1.0, c2: float | np.ndarray = 0.0, epsilon_a: float | np.ndarray = 0.2, epsilon_r: float | np.ndarray = 0.2, delta: float = 1e-2, ) -> dict[str, DPhiIndicators]: """Computes the D-PHI and CI indicators for multiple solution sets. Note: The minimization of the objective function values is assumed. Args: solution_sets (dict[str, np.ndarray]): A dict of strings mapped to 2D numpy arrays where each array contains a set of solutions. The keys of the dict are the names of the sets. The sets must have the same number of objectives/columns but can have a different number of solutions/rows. aspiration_point (float | np.ndarray): The aspiration point, shared by all the sets. reservation_point (float | np.ndarray): The reservation point, shared by all the sets. c1 (float | np.ndarray, optional): The desirability of the aspiration levels. Defaults to 1.0. c2 (float | np.ndarray, optional): The desirability of the reservation levels. Defaults to 0.0. epsilon_a (float | np.ndarray, optional): The upper limit parameter. Defaults to 0.2. epsilon_r (float | np.ndarray, optional): The lower limit parameter. Defaults to 0.2. delta (float, optional): A small positive number, see `d_phi_indicator`. Defaults to 1e-2. Returns: dict[str, DPhiIndicators]: A dict of strings mapped to DPhiIndicators objects. The keys of the dict are the names of the sets. """ return { set_name: d_phi_indicator( sols, aspiration_point, reservation_point, c1=c1, c2=c2, epsilon_a=epsilon_a, epsilon_r=epsilon_r, delta=delta, ) for set_name, sols in solution_sets.items() } ``` ### d_phi_indicator ``` d_phi_indicator( solution_set: ndarray, aspiration_point: float | ndarray, reservation_point: float | ndarray, *, c1: float | ndarray = 1.0, c2: float | ndarray = 0.0, epsilon_a: float | ndarray = 0.2, epsilon_r: float | ndarray = 0.2, delta: float = 0.01, ) -> DPhiIndicators ``` Computes the D-PHI indicator and its complementary indicator (CI) for a given solution set. D-PHI measures the quality of a solution set with respect to preferences expressed as an aspiration point and a reservation point. The solutions are first mapped to desirability values, see `desirability_values`, and D-PHI is the hypervolume of the mapped set, maximized, with the vector of lower limits `c2 - epsilon_r` as the reference point. Because the desirability function is bounded, D-PHI is bounded as well, and it is at most `prod(c1 + epsilon_a - c2 + epsilon_r)` over the objectives. D-PHI is insensitive to how close the set gets to the aspiration levels once the region between the aspiration and reservation points has been covered. The complementary indicator CI is reported alongside it for that reason: it is the negated achievement scalarizing function value of the best solution in the set, computed with the aspiration point as the reference point and `1 / (r - a)` as the weights. CI is non-negative if and only if some solution reaches every aspiration level. Note The minimization of the objective function values is assumed. Parameters: | Name | Type | Description | Default | | ------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `solution_set` | `ndarray` | A 2D numpy array where each row is a solution and each column is an objective value. D-PHI itself does not perform normalization. The set need not be mutually non-dominated, since dominated solutions do not affect the hypervolume. | *required* | | `aspiration_point` | \`float | ndarray\` | The aspiration point, containing one aspiration level per objective. A scalar is broadcast to all objectives. | | `reservation_point` | \`float | ndarray\` | The reservation point, consisting of the reservation level of each objective. A scalar is broadcast to all objectives. | | `c1` | \`float | ndarray\` | The desirability of the aspiration levels. Defaults to 1.0. | | `c2` | \`float | ndarray\` | The desirability of the reservation levels. Defaults to 0.0. | | `epsilon_a` | \`float | ndarray\` | A positive number defining the upper limit of the desirability function. Defaults to 0.2. | | `epsilon_r` | \`float | ndarray\` | A positive number defining the lower limit of the desirability function, which is also used as the reference point of the hypervolume computation. Defaults to 0.2. | | `delta` | `float` | A small positive number used in place of a - r for objectives where the aspiration and reservation levels coincide. Defaults to 1e-2. | `0.01` | Returns: | Name | Type | Description | | ---------------- | ---------------- | -------------------------------------------------------------- | | `DPhiIndicators` | `DPhiIndicators` | A Pydantic class containing the D-PHI and CI indicator values. | Raises: | Type | Description | | ------------ | ----------------------------------------------------------------------------------------------- | | `ValueError` | If solution_set is empty, or if the preference information is invalid, see desirability_values. | References Liang, M., Shavazipour, B., Saini, B., & Emmerich, M. (2026). D-PHI: Desirability-based hypervolume indicator for interactive multiobjective optimization using aspiration and reservation levels as preferences. ACM Transactions on Evolutionary Learning and Optimization. https://doi.org/10.1145/3794854 Source code in `desdeo/tools/indicators_unary.py` ``` def d_phi_indicator( solution_set: np.ndarray, aspiration_point: float | np.ndarray, reservation_point: float | np.ndarray, *, c1: float | np.ndarray = 1.0, c2: float | np.ndarray = 0.0, epsilon_a: float | np.ndarray = 0.2, epsilon_r: float | np.ndarray = 0.2, delta: float = 1e-2, ) -> DPhiIndicators: """Computes the D-PHI indicator and its complementary indicator (CI) for a given solution set. D-PHI measures the quality of a solution set with respect to preferences expressed as an aspiration point and a reservation point. The solutions are first mapped to desirability values, see `desirability_values`, and D-PHI is the hypervolume of the mapped set, maximized, with the vector of lower limits `c2 - epsilon_r` as the reference point. Because the desirability function is bounded, D-PHI is bounded as well, and it is at most `prod(c1 + epsilon_a - c2 + epsilon_r)` over the objectives. D-PHI is insensitive to how close the set gets to the aspiration levels once the region between the aspiration and reservation points has been covered. The complementary indicator CI is reported alongside it for that reason: it is the negated achievement scalarizing function value of the best solution in the set, computed with the aspiration point as the reference point and `1 / (r - a)` as the weights. CI is non-negative if and only if some solution reaches every aspiration level. Note: The minimization of the objective function values is assumed. Args: solution_set (np.ndarray): A 2D numpy array where each row is a solution and each column is an objective value. D-PHI itself does not perform normalization. The set need not be mutually non-dominated, since dominated solutions do not affect the hypervolume. aspiration_point (float | np.ndarray): The aspiration point, containing one aspiration level per objective. A scalar is broadcast to all objectives. reservation_point (float | np.ndarray): The reservation point, consisting of the reservation level of each objective. A scalar is broadcast to all objectives. c1 (float | np.ndarray, optional): The desirability of the aspiration levels. Defaults to 1.0. c2 (float | np.ndarray, optional): The desirability of the reservation levels. Defaults to 0.0. epsilon_a (float | np.ndarray, optional): A positive number defining the upper limit of the desirability function. Defaults to 0.2. epsilon_r (float | np.ndarray, optional): A positive number defining the lower limit of the desirability function, which is also used as the reference point of the hypervolume computation. Defaults to 0.2. delta (float, optional): A small positive number used in place of `a - r` for objectives where the aspiration and reservation levels coincide. Defaults to 1e-2. Returns: DPhiIndicators: A Pydantic class containing the D-PHI and CI indicator values. Raises: ValueError: If `solution_set` is empty, or if the preference information is invalid, see `desirability_values`. References: Liang, M., Shavazipour, B., Saini, B., & Emmerich, M. (2026). D-PHI: Desirability-based hypervolume indicator for interactive multiobjective optimization using aspiration and reservation levels as preferences. ACM Transactions on Evolutionary Learning and Optimization. https://doi.org/10.1145/3794854 """ solutions = np.atleast_2d(np.asarray(solution_set, dtype=float)) if solutions.size == 0: raise ValueError("'solution_set' must contain at least one solution.") num_objectives = solutions.shape[1] a = _as_objective_vector(aspiration_point, num_objectives, "aspiration_point") r = _as_objective_vector(reservation_point, num_objectives, "reservation_point") desirabilities = desirability_values( solutions, a, r, c1=c1, c2=c2, epsilon_a=epsilon_a, epsilon_r=epsilon_r, delta=delta ) # The lower limits of the desirability function are the reference point. No solution can reach them, so the # reference point is always dominated, and dominated solutions can be passed to the hypervolume as they are. reference_point = _as_objective_vector(c2, num_objectives, "c2") - _as_objective_vector( epsilon_r, num_objectives, "epsilon_r" ) hypervolume = Hypervolume(ref=reference_point, maximise=True) d_phi_value = hypervolume(desirabilities) if d_phi_value is None: raise ValueError("D-PHI calculation failed.") # CI: the negated ASF value of the best solution, with the aspiration point as the reference point. weights = 1 / np.where(a < r, r - a, delta) ci_value = -np.min(np.max(weights * (solutions - a), axis=1)) return DPhiIndicators(d_phi=float(d_phi_value), ci=float(ci_value)) ``` ### desirability_values ``` desirability_values( solution_set: ndarray, aspiration_point: float | ndarray, reservation_point: float | ndarray, *, c1: float | ndarray = 1.0, c2: float | ndarray = 0.0, epsilon_a: float | ndarray = 0.2, epsilon_r: float | ndarray = 0.2, delta: float = 0.01, ) -> np.ndarray ``` Maps objective vectors to desirability values using the desirability function of D-PHI. The desirability function is defined objective-wise and is piecewise: it is linear between the aspiration level `a` and the reservation level `r`, mapping `a` to `c1` and `r` to `c2`, and it is hyperbolic outside that interval. The hyperbolic pieces approach the limits `c1 + epsilon_a` (for values better than the aspiration level) and `c2 - epsilon_r` (for values worse than the reservation level) without ever reaching them, so the desirability values are always in the open interval `(c2 - epsilon_r, c1 + epsilon_a)`. Note The minimization of the objective function values is assumed, and desirability values are maximized. Parameters: | Name | Type | Description | Default | | ------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `solution_set` | `ndarray` | A 2D numpy array where each row is a solution and each column is an objective value. | *required* | | `aspiration_point` | \`float | ndarray\` | The aspiration point, containing one aspiration level per objective. A scalar is broadcast to all objectives. | | `reservation_point` | \`float | ndarray\` | The reservation point, consisting of the reservation level of each objective. A scalar is broadcast to all objectives. Each reservation level must be at least as large as the corresponding aspiration level. | | `c1` | \`float | ndarray\` | The desirability of the aspiration levels. Defaults to 1.0. | | `c2` | \`float | ndarray\` | The desirability of the reservation levels. Must be smaller than c1. Defaults to 0.0. | | `epsilon_a` | \`float | ndarray\` | A positive number defining the upper limit c1 + epsilon_a of the desirability function, controlling how much solutions better than the aspiration levels are rewarded. Defaults to 0.2. | | `epsilon_r` | \`float | ndarray\` | A positive number defining the lower limit c2 - epsilon_r of the desirability function, controlling how much solutions worse than the reservation levels are penalized. Defaults to 0.2. | | `delta` | `float` | A small positive number used in place of a - r for objectives where the aspiration and reservation levels coincide, keeping the desirability function well defined. Defaults to 1e-2. | `0.01` | Returns: | Type | Description | | --------- | -------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: A 2D numpy array of the same shape as solution_set containing the desirability values. | Raises: | Type | Description | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `ValueError` | If the arguments are of incompatible lengths, if any aspiration level is larger than the corresponding reservation level, if c1 is not larger than c2, or if delta, epsilon_a, or epsilon_r is not positive. | Source code in `desdeo/tools/indicators_unary.py` ``` def desirability_values( solution_set: np.ndarray, aspiration_point: float | np.ndarray, reservation_point: float | np.ndarray, *, c1: float | np.ndarray = 1.0, c2: float | np.ndarray = 0.0, epsilon_a: float | np.ndarray = 0.2, epsilon_r: float | np.ndarray = 0.2, delta: float = 1e-2, ) -> np.ndarray: """Maps objective vectors to desirability values using the desirability function of D-PHI. The desirability function is defined objective-wise and is piecewise: it is linear between the aspiration level `a` and the reservation level `r`, mapping `a` to `c1` and `r` to `c2`, and it is hyperbolic outside that interval. The hyperbolic pieces approach the limits `c1 + epsilon_a` (for values better than the aspiration level) and `c2 - epsilon_r` (for values worse than the reservation level) without ever reaching them, so the desirability values are always in the open interval `(c2 - epsilon_r, c1 + epsilon_a)`. Note: The minimization of the objective function values is assumed, and desirability values are maximized. Args: solution_set (np.ndarray): A 2D numpy array where each row is a solution and each column is an objective value. aspiration_point (float | np.ndarray): The aspiration point, containing one aspiration level per objective. A scalar is broadcast to all objectives. reservation_point (float | np.ndarray): The reservation point, consisting of the reservation level of each objective. A scalar is broadcast to all objectives. Each reservation level must be at least as large as the corresponding aspiration level. c1 (float | np.ndarray, optional): The desirability of the aspiration levels. Defaults to 1.0. c2 (float | np.ndarray, optional): The desirability of the reservation levels. Must be smaller than `c1`. Defaults to 0.0. epsilon_a (float | np.ndarray, optional): A positive number defining the upper limit `c1 + epsilon_a` of the desirability function, controlling how much solutions better than the aspiration levels are rewarded. Defaults to 0.2. epsilon_r (float | np.ndarray, optional): A positive number defining the lower limit `c2 - epsilon_r` of the desirability function, controlling how much solutions worse than the reservation levels are penalized. Defaults to 0.2. delta (float, optional): A small positive number used in place of `a - r` for objectives where the aspiration and reservation levels coincide, keeping the desirability function well defined. Defaults to 1e-2. Returns: np.ndarray: A 2D numpy array of the same shape as `solution_set` containing the desirability values. Raises: ValueError: If the arguments are of incompatible lengths, if any aspiration level is larger than the corresponding reservation level, if `c1` is not larger than `c2`, or if `delta`, `epsilon_a`, or `epsilon_r` is not positive. """ solutions = np.atleast_2d(np.asarray(solution_set, dtype=float)) num_objectives = solutions.shape[1] a = _as_objective_vector(aspiration_point, num_objectives, "aspiration_point") r = _as_objective_vector(reservation_point, num_objectives, "reservation_point") c1 = _as_objective_vector(c1, num_objectives, "c1") c2 = _as_objective_vector(c2, num_objectives, "c2") epsilon_a = _as_objective_vector(epsilon_a, num_objectives, "epsilon_a") epsilon_r = _as_objective_vector(epsilon_r, num_objectives, "epsilon_r") if delta <= 0: raise ValueError(f"'delta' must be positive, got {delta}.") if np.any(a > r): raise ValueError("Each aspiration level must be at most as large as the corresponding reservation level.") if np.any(c1 <= c2): raise ValueError("Each component of 'c1' must be larger than the corresponding component of 'c2'.") if np.any(epsilon_a <= 0) or np.any(epsilon_r <= 0): raise ValueError("'epsilon_a' and 'epsilon_r' must be positive.") # 'a - r' must be strictly negative. Objectives with a == r are handled by substituting -delta. a_minus_r = np.where(a < r, a - r, -delta) # The inverse slope of the linear piece, always negative. inverse_slope = a_minus_r / (c1 - c2) desirabilities = np.empty_like(solutions) better_than_a = solutions <= a worse_than_r = solutions > r between = ~better_than_a & ~worse_than_r # Broadcast the objective-wise parameters over the solutions. a_full, c1_full = np.broadcast_to(a, solutions.shape), np.broadcast_to(c1, solutions.shape) r_full, c2_full = np.broadcast_to(r, solutions.shape), np.broadcast_to(c2, solutions.shape) eps_a_full, eps_r_full = np.broadcast_to(epsilon_a, solutions.shape), np.broadcast_to(epsilon_r, solutions.shape) a_minus_r_full = np.broadcast_to(a_minus_r, solutions.shape) inverse_slope_full = np.broadcast_to(inverse_slope, solutions.shape) # Better than the aspiration levels: a hyperbola approaching c1 + epsilon_a from below. mask = better_than_a desirabilities[mask] = -(eps_a_full[mask] ** 2) * inverse_slope_full[mask] / ( solutions[mask] - a_full[mask] + eps_a_full[mask] * inverse_slope_full[mask] ) + (c1_full[mask] + eps_a_full[mask]) # Between the aspiration and reservation levels: linear from c1 to c2. mask = between desirabilities[mask] = ( (c1_full[mask] - c2_full[mask]) * solutions[mask] - c1_full[mask] * r_full[mask] + c2_full[mask] * a_full[mask] ) / a_minus_r_full[mask] # Worse than the reservation levels: a hyperbola approaching c2 - epsilon_r from above. mask = worse_than_r desirabilities[mask] = -(eps_r_full[mask] ** 2) * inverse_slope_full[mask] / ( solutions[mask] - r_full[mask] - eps_r_full[mask] * inverse_slope_full[mask] ) + (c2_full[mask] - eps_r_full[mask]) return desirabilities ``` ### distance_indicators ``` distance_indicators( solution_set: ndarray, reference_set: ndarray, p: float = 2.0, distance_p: float = 2.0, ) -> DistanceIndicators ``` Calculates various distance based indicators between a solution set and a reference set. Given the point-to-set distances `d_i`, the indicators are ``` IGD = mean over the reference set of the distance to the closest solution, GD = mean over the solution set of the distance to the closest reference point, IGD_p = (mean(d_i**p))**(1/p) over the reference set, GD_p = (mean(d_i**p))**(1/p) over the solution set, AHD = max(IGD_p, GD_p), the averaged Hausdorff distance Delta_p. ``` Note that `p` only controls the averaging; the point-to-point distance is controlled separately by `distance_p` and defaults to the Euclidean distance, matching the definitions used by `moocore` and by Schuetze et al. Consequently, IGD_p and GD_p coincide with IGD and GD when `p == 1`. Parameters: | Name | Type | Description | Default | | --------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | | `solution_set` | `ndarray` | A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. The solutions are assumed to be non-dominated. | *required* | | `reference_set` | `ndarray` | A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the reference set should probably be (0, 0, ..., 0) and (1, 1, ..., 1) respectively. The reference set is assumed to be non-dominated. | *required* | | `p` | `float` | The order of the generalized mean used to aggregate the distances into IGD_p, GD_p, and AHD. Must be positive; np.inf (or math.inf) aggregates by taking the maximum distance, giving the (non-averaged) Hausdorff distance. Defaults to 2.0. | `2.0` | | `distance_p` | `float` | The power of the Minkowski metric used for the point-to-point distances. Set to 1 for Manhattan distance, 2 for Euclidean distance, and np.inf (or math.inf) for Chebyshev distance. Defaults to 2.0, i.e., the Euclidean distance used by the standard definitions of these indicators. | `2.0` | Returns: | Name | Type | Description | | -------------------- | -------------------- | ------------------------------------------------------------------------------- | | `DistanceIndicators` | `DistanceIndicators` | A Pydantic class containing the IGD, IGD_p, GD, GD_p, and AHD indicator values. | Raises: | Type | Description | | ------------ | ----------------------------------- | | `ValueError` | If p or distance_p is not positive. | Source code in `desdeo/tools/indicators_unary.py` ``` def distance_indicators( solution_set: np.ndarray, reference_set: np.ndarray, p: float = 2.0, distance_p: float = 2.0 ) -> DistanceIndicators: """Calculates various distance based indicators between a solution set and a reference set. Given the point-to-set distances `d_i`, the indicators are IGD = mean over the reference set of the distance to the closest solution, GD = mean over the solution set of the distance to the closest reference point, IGD_p = (mean(d_i**p))**(1/p) over the reference set, GD_p = (mean(d_i**p))**(1/p) over the solution set, AHD = max(IGD_p, GD_p), the averaged Hausdorff distance Delta_p. Note that `p` only controls the averaging; the point-to-point distance is controlled separately by `distance_p` and defaults to the Euclidean distance, matching the definitions used by `moocore` and by Schuetze et al. Consequently, IGD_p and GD_p coincide with IGD and GD when `p == 1`. Args: solution_set (np.ndarray): A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. The solutions are assumed to be non-dominated. reference_set (np.ndarray): A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the reference set should probably be (0, 0, ..., 0) and (1, 1, ..., 1) respectively. The reference set is assumed to be non-dominated. p (float, optional): The order of the generalized mean used to aggregate the distances into IGD_p, GD_p, and AHD. Must be positive; np.inf (or math.inf) aggregates by taking the maximum distance, giving the (non-averaged) Hausdorff distance. Defaults to 2.0. distance_p (float, optional): The power of the Minkowski metric used for the point-to-point distances. Set to 1 for Manhattan distance, 2 for Euclidean distance, and np.inf (or math.inf) for Chebyshev distance. Defaults to 2.0, i.e., the Euclidean distance used by the standard definitions of these indicators. Returns: DistanceIndicators: A Pydantic class containing the IGD, IGD_p, GD, GD_p, and AHD indicator values. Raises: ValueError: If `p` or `distance_p` is not positive. """ if p <= 0: raise ValueError(f"'p' must be positive, got {p}.") if distance_p <= 0: raise ValueError(f"'distance_p' must be positive, got {distance_p}.") distance_matrix = cdist(solution_set, reference_set, metric="minkowski", p=distance_p) # For each reference point, the distance to the closest solution, and vice versa. igd_distances = np.min(distance_matrix, axis=0) gd_distances = np.min(distance_matrix, axis=1) _igd = float(igd_distances.mean()) _gd = float(gd_distances.mean()) _igd_p = _power_mean(igd_distances, p) _gd_p = _power_mean(gd_distances, p) _ahd = max(_igd_p, _gd_p) return DistanceIndicators(igd=_igd, igd_p=_igd_p, gd=_gd, gd_p=_gd_p, ahd=_ahd) ``` ### distance_indicators_batch ``` distance_indicators_batch( solution_sets: dict[str, ndarray], reference_set: ndarray, p: float = 2.0, distance_p: float = 2.0, ) -> dict[str, DistanceIndicators] ``` Calculate the IGD, GD, GD_p, IGD_p, and AHD for a sets of solutions. Parameters: | Name | Type | Description | Default | | --------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `solution_sets` | `dict[str, ndarray]` | A dict of strings mapped to 2D numpy arrays where each array contains a set of solutions. Each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. The solutions are assumed to be non-dominated within their respective sets. The sets must have the same number of objectives/columns but can have different number of solutions/rows. The keys of the dict are the names of the sets. | *required* | | `reference_set` | `ndarray` | A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the reference set should probably be (0, 0, ..., 0) and (1, 1, ..., 1) respectively. The reference set is assumed to be non-dominated. | *required* | | `p` | `float` | The order of the generalized mean used to aggregate the distances into IGD_p, GD_p, and AHD. Must be positive; np.inf (or math.inf) aggregates by taking the maximum distance. Defaults to 2.0. | `2.0` | | `distance_p` | `float` | The power of the Minkowski metric used for the point-to-point distances. Set to 1 for Manhattan distance, 2 for Euclidean distance, and np.inf (or math.inf) for Chebyshev distance. Defaults to 2.0, i.e., the Euclidean distance used by the standard definitions of these indicators. | `2.0` | Returns: | Type | Description | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dict[str, DistanceIndicators]` | dict\[str, DistanceIndicators\]: A dict of strings mapped to DistanceIndicators objects. The keys of the dict are the names of the sets. The DistanceIndicators objects contain the IGD, IGD_p, GD, GD_p, and AHD indicator values. This data structure can be easily converted to a DataFrame or saved to disk as a JSON file. | Source code in `desdeo/tools/indicators_unary.py` ``` def distance_indicators_batch( solution_sets: dict[str, np.ndarray], reference_set: np.ndarray, p: float = 2.0, distance_p: float = 2.0 ) -> dict[str, DistanceIndicators]: """Calculate the IGD, GD, GD_p, IGD_p, and AHD for a sets of solutions. Args: solution_sets (dict[str, np.ndarray]): A dict of strings mapped to 2D numpy arrays where each array contains a set of solutions. Each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. The solutions are assumed to be non-dominated within their respective sets. The sets must have the same number of objectives/columns but can have different number of solutions/rows. The keys of the dict are the names of the sets. reference_set (np.ndarray): A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the reference set should probably be (0, 0, ..., 0) and (1, 1, ..., 1) respectively. The reference set is assumed to be non-dominated. p (float, optional): The order of the generalized mean used to aggregate the distances into IGD_p, GD_p, and AHD. Must be positive; np.inf (or math.inf) aggregates by taking the maximum distance. Defaults to 2.0. distance_p (float, optional): The power of the Minkowski metric used for the point-to-point distances. Set to 1 for Manhattan distance, 2 for Euclidean distance, and np.inf (or math.inf) for Chebyshev distance. Defaults to 2.0, i.e., the Euclidean distance used by the standard definitions of these indicators. Returns: dict[str, DistanceIndicators]: A dict of strings mapped to DistanceIndicators objects. The keys of the dict are the names of the sets. The DistanceIndicators objects contain the IGD, IGD_p, GD, GD_p, and AHD indicator values. This data structure can be easily converted to a DataFrame or saved to disk as a JSON file. """ inds = {} for set_name, sols in solution_sets.items(): inds[set_name] = distance_indicators(sols, reference_set, p=p, distance_p=distance_p) return inds ``` ### get_pareto_front ``` get_pareto_front(solutions) ``` Extract the Pareto front from a set of solutions. Source code in `desdeo/tools/indicators_unary.py` ``` def get_pareto_front(solutions): """Extract the Pareto front from a set of solutions.""" pareto_front = [] for i, solution in enumerate(solutions): remaining_solutions = np.delete(solutions, i, axis=0) if not is_dominated(solution, remaining_solutions): pareto_front.append(solution) return np.array(pareto_front) ``` ### hv ``` hv( solution_set: ndarray, reference_point_component: float ) -> float ``` Calculate the hypervolume indicator for a set of solutions. Parameters: | Name | Type | Description | Default | | --------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `solution_set` | `ndarray` | A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be non-dominated. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. | *required* | | `reference_point_component` | `float` | The value of the reference point component. The reference point is assumed to be the same for all objectives. The reference point must be at least 1. | *required* | Returns: | Name | Type | Description | | ------- | ------- | -------------------------------- | | `float` | `float` | The hypervolume indicator value. | Source code in `desdeo/tools/indicators_unary.py` ``` def hv(solution_set: np.ndarray, reference_point_component: float) -> float: """Calculate the hypervolume indicator for a set of solutions. Args: solution_set (np.ndarray): A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be non-dominated. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. reference_point_component (float): The value of the reference point component. The reference point is assumed to be the same for all objectives. The reference point must be at least 1. Returns: float: The hypervolume indicator value. """ hv = Hypervolume(reference_point_component) ind = hv(solution_set) if ind is None: raise ValueError("Hypervolume calculation failed.") return float(ind) ``` ### hv_batch ``` hv_batch( solution_sets: dict[str, ndarray], reference_points_component: list[float], ) -> dict[str, list[float | None]] ``` Calculate the hypervolume indicator for a set of solutions over a range of reference points. Parameters: | Name | Type | Description | Default | | ---------------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `solution_sets` | `dict[str, ndarray]` | A dict of strings mapped to 2D numpy arrays where each array contains a set of solutions. Each row is a solution and each column is an objective value. The solutions are assumed to be non-dominated within their respective sets. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. The sets must have the same number of objectives/columns but can have different number of solutions/rows. The keys of the dict are the names of the sets. | *required* | | `reference_points_component` | `list[float]` | A list of the value of the reference point component. The hypervolume is calculated for each set of solutions for each reference point component. The reference point is assumed to be the same for all objectives. The reference point must be at least 1. | *required* | Returns: | Type | Description | | ------------------------ | ----------- | | \`dict\[str, list\[float | None\]\]\` | Source code in `desdeo/tools/indicators_unary.py` ``` def hv_batch( solution_sets: dict[str, np.ndarray], reference_points_component: list[float] ) -> dict[str, list[float | None]]: """Calculate the hypervolume indicator for a set of solutions over a range of reference points. Args: solution_sets (dict[str, np.ndarray]): A dict of strings mapped to 2D numpy arrays where each array contains a set of solutions. Each row is a solution and each column is an objective value. The solutions are assumed to be non-dominated within their respective sets. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. The sets must have the same number of objectives/columns but can have different number of solutions/rows. The keys of the dict are the names of the sets. reference_points_component (list[float]): A list of the value of the reference point component. The hypervolume is calculated for each set of solutions for each reference point component. The reference point is assumed to be the same for all objectives. The reference point must be at least 1. Returns: dict[str, list[float | None]]: A dict of strings mapped to lists of hypervolume indicator values. The keys of the dict are the names of the sets. The lists contain the hypervolume indicator values for each reference point component. If the calculation fails, the value is set to None, and should be handled by the user. """ hvs = {key: [] for key in solution_sets} solution_sets[next(iter(solution_sets.keys()))].shape[1] for rp in reference_points_component: hv = Hypervolume(rp) for set_name, sols in solution_sets.items(): ind = hv(sols) if ind is None: warn("Hypervolume calculation failed. Setting value to None", category=RuntimeWarning, stacklevel=2) hvs[set_name].append(None) else: hvs[set_name].append(float(ind)) return hvs ``` ### igd_plus_batch ``` igd_plus_batch( solution_sets: dict[str, ndarray], reference_set: ndarray, p: float = 2.0, ) -> dict[str, IGDPlusIndicators] ``` Computes the IGD+ indicator for multiple solution sets. Notes The minimization of the objective function values is assumed. Parameters: | Name | Type | Description | Default | | --------------- | -------------------- | ------------------------------------------------------------------------ | ---------- | | `solution_sets` | `dict[str, ndarray]` | A dictionary of solution sets. | *required* | | `reference_set` | `ndarray` | The reference Pareto front. | *required* | | `p` | `float` | The power of the Minkowski metric. Defaults to 2.0 (Euclidean distance). | `2.0` | Returns: | Type | Description | | ------------------------------ | ------------------------------------------------------------------ | | `dict[str, IGDPlusIndicators]` | dict\[str, IGDPlusIndicators\]: A dictionary of IGDPlusIndicators. | Source code in `desdeo/tools/indicators_unary.py` ``` def igd_plus_batch( solution_sets: dict[str, np.ndarray], reference_set: np.ndarray, p: float = 2.0 ) -> dict[str, IGDPlusIndicators]: """Computes the IGD+ indicator for multiple solution sets. Notes: The minimization of the objective function values is assumed. Args: solution_sets (dict[str, np.ndarray]): A dictionary of solution sets. reference_set (np.ndarray): The reference Pareto front. p (float, optional): The power of the Minkowski metric. Defaults to 2.0 (Euclidean distance). Returns: dict[str, IGDPlusIndicators]: A dictionary of IGDPlusIndicators. """ results = {} for set_name, solution_set in solution_sets.items(): results[set_name] = igd_plus_indicator(solution_set, reference_set, p) return results ``` ### igd_plus_indicator ``` igd_plus_indicator( solution_set: ndarray, reference_set: ndarray, p: float = 2.0, ) -> IGDPlusIndicators ``` Computes the IGD+ indicator for a given solution set. Notes The minimization of the objective function values is assumed. IGD+ is defined by Ishibuchi et al. (2015) in terms of the Euclidean distance, i.e., p == 2, which is the default here. Other values of `p` give a non-standard generalization that will not match the IGD+ values reported by, e.g., `moocore` or `pymoo`. Parameters: | Name | Type | Description | Default | | --------------- | --------- | ------------------------------------------------------------------------ | ---------- | | `solution_set` | `ndarray` | The solution set being evaluated. | *required* | | `reference_set` | `ndarray` | The reference Pareto front. | *required* | | `p` | `float` | The power of the Minkowski metric. Defaults to 2.0 (Euclidean distance). | `2.0` | Returns: | Name | Type | Description | | ------------------- | ------------------- | ----------------------------------------------------- | | `IGDPlusIndicators` | `IGDPlusIndicators` | A Pydantic class containing the IGD+ indicator value. | Source code in `desdeo/tools/indicators_unary.py` ``` def igd_plus_indicator(solution_set: np.ndarray, reference_set: np.ndarray, p: float = 2.0) -> IGDPlusIndicators: """Computes the IGD+ indicator for a given solution set. Notes: The minimization of the objective function values is assumed. IGD+ is defined by Ishibuchi et al. (2015) in terms of the Euclidean distance, i.e., p == 2, which is the default here. Other values of `p` give a non-standard generalization that will not match the IGD+ values reported by, e.g., `moocore` or `pymoo`. Args: solution_set (np.ndarray): The solution set being evaluated. reference_set (np.ndarray): The reference Pareto front. p (float, optional): The power of the Minkowski metric. Defaults to 2.0 (Euclidean distance). Returns: IGDPlusIndicators: A Pydantic class containing the IGD+ indicator value. """ num_ref_points = reference_set.shape[0] total_distance = 0.0 for y_p in reference_set: min_distance = float("inf") for y_n in solution_set: # Compute IGD+ distance (only positive differences) distance = np.sum(np.maximum(0, y_n - y_p) ** p) # Sum over objectives min_distance = min(min_distance, distance) # Store the closest one total_distance += min_distance ** (1 / p) # Apply the root AFTER summing over objectives igd_plus_value = total_distance / num_ref_points return IGDPlusIndicators(igd_plus=igd_plus_value) ``` ### is_dominated ``` is_dominated(solution, other_solutions) ``` Check if a solution is dominated by any other solution. Source code in `desdeo/tools/indicators_unary.py` ``` def is_dominated(solution, other_solutions): """Check if a solution is dominated by any other solution.""" return any(np.all(other <= solution) and np.any(other < solution) for other in other_solutions) ``` ### phi_plus_batch ``` phi_plus_batch( solution_sets: dict[str, ndarray], reference_point: float | ndarray, deviations_lower: float | ndarray, deviations_upper: float | ndarray, ) -> dict[str, PhiPlusIndicator] ``` Computes the PHI+ indicator for multiple solution sets. Note The minimization of the objective function values is assumed. Parameters: | Name | Type | Description | Default | | ------------------ | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | `solution_sets` | `dict[str, ndarray]` | A dict of strings mapped to 2D numpy arrays where each array contains a set of solutions. The keys of the dict are the names of the sets. The sets must have the same number of objectives/columns but can have a different number of solutions/rows. | *required* | | `reference_point` | \`float | ndarray\` | The reference point of the decision maker, shared by all the sets. | | `deviations_lower` | \`float | ndarray\` | The distances to the lower boundary of the region of interest. | | `deviations_upper` | \`float | ndarray\` | The distances to the upper boundary of the region of interest. | Returns: | Type | Description | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `dict[str, PhiPlusIndicator]` | dict\[str, PhiPlusIndicator\]: A dict of strings mapped to PhiPlusIndicator objects. The keys of the dict are the names of the sets. | Source code in `desdeo/tools/indicators_unary.py` ``` def phi_plus_batch( solution_sets: dict[str, np.ndarray], reference_point: float | np.ndarray, deviations_lower: float | np.ndarray, deviations_upper: float | np.ndarray, ) -> dict[str, PhiPlusIndicator]: """Computes the PHI+ indicator for multiple solution sets. Note: The minimization of the objective function values is assumed. Args: solution_sets (dict[str, np.ndarray]): A dict of strings mapped to 2D numpy arrays where each array contains a set of solutions. The keys of the dict are the names of the sets. The sets must have the same number of objectives/columns but can have a different number of solutions/rows. reference_point (float | np.ndarray): The reference point of the decision maker, shared by all the sets. deviations_lower (float | np.ndarray): The distances to the lower boundary of the region of interest. deviations_upper (float | np.ndarray): The distances to the upper boundary of the region of interest. Returns: dict[str, PhiPlusIndicator]: A dict of strings mapped to PhiPlusIndicator objects. The keys of the dict are the names of the sets. """ return { set_name: phi_plus_indicator(sols, reference_point, deviations_lower, deviations_upper) for set_name, sols in solution_sets.items() } ``` ### phi_plus_indicator ``` phi_plus_indicator( solution_set: ndarray, reference_point: float | ndarray, deviations_lower: float | ndarray, deviations_upper: float | ndarray, ) -> PhiPlusIndicator ``` Computes the PHI+ indicator for a given solution set. PHI+ measures how well a solution set covers a region of interest around a reference point given by a decision maker. The region of interest is the box spanned by the lower point `reference_point - deviations_lower` and the upper point `reference_point + deviations_upper`. Solutions inside that box, as well as any solution dominating the reference point, are taken into account; everything else is discarded. The indicator is the hypervolume of the retained solutions, computed with the upper point as the reference point, divided by the largest hypervolume that solutions in the region of interest could attain. The normalizing quantity depends on whether the reference point is attainable: if some solution dominates the reference point, the hypervolume of the reference point itself is used; otherwise the hypervolume of the lower point minus the volume of the box between the lower point and the reference point is used, since no solution can occupy that box. The indicator is 0 when the region of interest contains no solutions, and it exceeds 1 when the set contains solutions better than the reference point. Note The minimization of the objective function values is assumed. Following the assumptions of this module, the solution set, the reference point, and the deviations are all expected to be given in the same normalized objective space, and no further normalization is applied here. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `solution_set` | `ndarray` | A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. Dominated solutions are filtered out before the indicator is computed. | *required* | | `reference_point` | \`float | ndarray\` | The reference point of the decision maker, given in the same normalized objective space as the solutions. | | `deviations_lower` | \`float | ndarray\` | The distance from the reference point to the lower (better) boundary of the region of interest, per objective. Must be non-negative; zero means that the region of interest is not extended past the reference point in that direction. A scalar is broadcast to all objectives. | | `deviations_upper` | \`float | ndarray\` | The distance from the reference point to the upper (worse) boundary of the region of interest, per objective. Must be positive so that the hypervolume between the reference point and the upper point is strictly positive. A scalar is broadcast to all objectives. | Returns: | Name | Type | Description | | ------------------ | ------------------ | ----------------------------------------------------- | | `PhiPlusIndicator` | `PhiPlusIndicator` | A Pydantic class containing the PHI+ indicator value. | Raises: | Type | Description | | ------------ | ------------------------------------------------------------------------------------------------------------------------------- | | `ValueError` | If the deviations are of an incompatible length, if any lower deviation is negative, or if any upper deviation is not positive. | References Liang, M., Shavazipour, B., Saini, B., Emmerich, M., & Miettinen, K. (2024). A modified preference-based hypervolume indicator for interactive evolutionary multiobjective optimization methods. In Proceedings of the 16th International Joint Conference on Computational Intelligence (pp. 214-221). SCITEPRESS. Source code in `desdeo/tools/indicators_unary.py` ``` def phi_plus_indicator( solution_set: np.ndarray, reference_point: float | np.ndarray, deviations_lower: float | np.ndarray, deviations_upper: float | np.ndarray, ) -> PhiPlusIndicator: """Computes the PHI+ indicator for a given solution set. PHI+ measures how well a solution set covers a region of interest around a reference point given by a decision maker. The region of interest is the box spanned by the lower point `reference_point - deviations_lower` and the upper point `reference_point + deviations_upper`. Solutions inside that box, as well as any solution dominating the reference point, are taken into account; everything else is discarded. The indicator is the hypervolume of the retained solutions, computed with the upper point as the reference point, divided by the largest hypervolume that solutions in the region of interest could attain. The normalizing quantity depends on whether the reference point is attainable: if some solution dominates the reference point, the hypervolume of the reference point itself is used; otherwise the hypervolume of the lower point minus the volume of the box between the lower point and the reference point is used, since no solution can occupy that box. The indicator is 0 when the region of interest contains no solutions, and it exceeds 1 when the set contains solutions better than the reference point. Note: The minimization of the objective function values is assumed. Following the assumptions of this module, the solution set, the reference point, and the deviations are all expected to be given in the same normalized objective space, and no further normalization is applied here. Args: solution_set (np.ndarray): A 2D numpy array where each row is a solution and each column is an objective value. The solutions are assumed to be normalized within the unit hypercube. The ideal and nadir of the set itself can lie within the hypercube, but not outside it. Dominated solutions are filtered out before the indicator is computed. reference_point (float | np.ndarray): The reference point of the decision maker, given in the same normalized objective space as the solutions. deviations_lower (float | np.ndarray): The distance from the reference point to the lower (better) boundary of the region of interest, per objective. Must be non-negative; zero means that the region of interest is not extended past the reference point in that direction. A scalar is broadcast to all objectives. deviations_upper (float | np.ndarray): The distance from the reference point to the upper (worse) boundary of the region of interest, per objective. Must be positive so that the hypervolume between the reference point and the upper point is strictly positive. A scalar is broadcast to all objectives. Returns: PhiPlusIndicator: A Pydantic class containing the PHI+ indicator value. Raises: ValueError: If the deviations are of an incompatible length, if any lower deviation is negative, or if any upper deviation is not positive. References: Liang, M., Shavazipour, B., Saini, B., Emmerich, M., & Miettinen, K. (2024). A modified preference-based hypervolume indicator for interactive evolutionary multiobjective optimization methods. In Proceedings of the 16th International Joint Conference on Computational Intelligence (pp. 214-221). SCITEPRESS. """ solutions = np.atleast_2d(np.asarray(solution_set, dtype=float)) if solutions.size == 0: return PhiPlusIndicator(phi_plus=0.0) num_objectives = solutions.shape[1] rp = _as_objective_vector(reference_point, num_objectives, "reference_point") dev_lower = _as_objective_vector(deviations_lower, num_objectives, "deviations_lower") dev_upper = _as_objective_vector(deviations_upper, num_objectives, "deviations_upper") if np.any(dev_lower < 0): raise ValueError("'deviations_lower' must be non-negative.") if np.any(dev_upper <= 0): raise ValueError("'deviations_upper' must be positive to keep the PHI+ normalization denominator well defined.") lower_point = rp - dev_lower upper_point = rp + dev_upper non_dominated_solutions = solutions[non_dominated(solutions)] # Solutions inside the box spanned by the lower and the upper point, plus any solution dominating the # reference point, form the (modified) region of interest. in_box = np.all((non_dominated_solutions >= lower_point) & (non_dominated_solutions <= upper_point), axis=1) dominates_rp = np.all(non_dominated_solutions < rp, axis=1) in_region = in_box | dominates_rp solutions_in_region = non_dominated_solutions[in_region] if solutions_in_region.size == 0: return PhiPlusIndicator(phi_plus=0.0) # Positive upper deviations guarantee that the reference point dominates the upper point, so both of the # normalizing quantities below are strictly positive. hypervolume = Hypervolume(ref=upper_point) if np.any(dominates_rp): # The reference point is attainable, so the whole of its hypervolume can be covered. best_possible = hypervolume(rp.reshape(1, -1)) else: # No solution dominates the reference point, so the box between the lower point and the reference point # is unreachable and is subtracted from the hypervolume of the lower point. best_possible = hypervolume(lower_point.reshape(1, -1)) - np.prod(dev_lower) return PhiPlusIndicator(phi_plus=float(hypervolume(solutions_in_region) / best_possible)) ``` ### r2_batch ``` r2_batch( solution_sets: dict[str, ndarray], lambda_set: ndarray, z_star: ndarray, rho: float = 0.05, ) -> dict[str, R2Indicator] ``` Computes the R2 indicator for multiple solution sets. Parameters: | Name | Type | Description | Default | | --------------- | -------------------- | -------------------------------- | ---------- | | `solution_sets` | `dict[str, ndarray]` | Dictionary of solution sets. | *required* | | `lambda_set` | `ndarray` | Set of weight vectors. | *required* | | `z_star` | `ndarray` | Ideal point. | *required* | | `rho` | `float` | Augmented Tchebycheff parameter. | `0.05` | Returns: | Type | Description | | ------------------------ | ------------------------------------------------------ | | `dict[str, R2Indicator]` | dict\[str, R2IndicatorResult\]: Dictionary of results. | Source code in `desdeo/tools/indicators_unary.py` ``` def r2_batch( solution_sets: dict[str, np.ndarray], lambda_set: np.ndarray, z_star: np.ndarray, rho: float = 0.05 ) -> dict[str, R2Indicator]: """Computes the R2 indicator for multiple solution sets. Args: solution_sets (dict[str, np.ndarray]): Dictionary of solution sets. lambda_set (np.ndarray): Set of weight vectors. z_star (np.ndarray): Ideal point. rho (float, optional): Augmented Tchebycheff parameter. Returns: dict[str, R2IndicatorResult]: Dictionary of results. """ return {name: r2_indicator(solution_set, lambda_set, z_star, rho) for name, solution_set in solution_sets.items()} ``` ### r2_indicator ``` r2_indicator( solution_set: ndarray, lambda_set: ndarray, z_star: ndarray, rho: float = 0.05, ) -> R2Indicator ``` Computes the unary R2 indicator for a given solution set. **Higher is better, and the value is always negative** -- the opposite of every other indicator in this module, and the single most likely thing to be got wrong about it. Two conventions for unary R2 are in use and they differ by a sign. This is the *utility* form of Brockhoff, Wagner and Trautmann: the mean over weight vectors of the best utility any solution achieves, where the utility is a negated Tchebycheff distance. PlatEMO and jMetal report the *distance* form instead -- the mean over weight vectors of the smallest Tchebycheff distance -- which is non-negative and minimised. The two are exact negations of each other, so `-r2_value` converts this to the value those frameworks print. Parameters: | Name | Type | Description | Default | | -------------- | --------- | ----------------------------------------------------------------- | ---------- | | `solution_set` | `ndarray` | The Pareto front approximation. | *required* | | `lambda_set` | `ndarray` | The set of normalized weight vectors (λ). | *required* | | `z_star` | `ndarray` | The ideal point (must dominate or weakly dominate all solutions). | *required* | | `rho` | `float` | Small positive number for augmented Tchebycheff. Default is 0.05. | `0.05` | Returns: | Name | Type | Description | | ------------------- | ------------- | ---------------------------------------------------------- | | `R2IndicatorResult` | `R2Indicator` | Pydantic class with R2 value. Higher is better; see above. | References Brockhoff, D., Wagner, T., & Trautmann, H. (2012). On the properties of the R2 indicator. In Proceedings of the 14th Annual Conference on Genetic and Evolutionary Computation (pp. 465-472). https://doi.org/10.1145/2330163.2330230 Hansen, M. P., & Jaszkiewicz, A. (1998). Evaluating the quality of approximations to the non-dominated set. IMM Technical Report IMM-REP-1998-7, Technical University of Denmark. Source code in `desdeo/tools/indicators_unary.py` ``` def r2_indicator( solution_set: np.ndarray, lambda_set: np.ndarray, z_star: np.ndarray, rho: float = 0.05 ) -> R2Indicator: """Computes the unary R2 indicator for a given solution set. **Higher is better, and the value is always negative** -- the opposite of every other indicator in this module, and the single most likely thing to be got wrong about it. Two conventions for unary R2 are in use and they differ by a sign. This is the *utility* form of Brockhoff, Wagner and Trautmann: the mean over weight vectors of the best utility any solution achieves, where the utility is a negated Tchebycheff distance. PlatEMO and jMetal report the *distance* form instead -- the mean over weight vectors of the smallest Tchebycheff distance -- which is non-negative and minimised. The two are exact negations of each other, so `-r2_value` converts this to the value those frameworks print. Args: solution_set (np.ndarray): The Pareto front approximation. lambda_set (np.ndarray): The set of normalized weight vectors (λ). z_star (np.ndarray): The ideal point (must dominate or weakly dominate all solutions). rho (float, optional): Small positive number for augmented Tchebycheff. Default is 0.05. Returns: R2IndicatorResult: Pydantic class with R2 value. Higher is better; see above. References: Brockhoff, D., Wagner, T., & Trautmann, H. (2012). On the properties of the R2 indicator. In Proceedings of the 14th Annual Conference on Genetic and Evolutionary Computation (pp. 465-472). https://doi.org/10.1145/2330163.2330230 Hansen, M. P., & Jaszkiewicz, A. (1998). Evaluating the quality of approximations to the non-dominated set. IMM Technical Report IMM-REP-1998-7, Technical University of Denmark. """ total_score = 0.0 for lambd in lambda_set: best_score = max(tchebycheff_utility(fx, lambd, z_star, rho) for fx in solution_set) total_score += best_score r2_value = total_score / len(lambda_set) return R2Indicator(r2_value=r2_value) ``` ### r_metric_indicator ``` r_metric_indicator( solution_set: ndarray, ref_points: ndarray, w: ndarray = None, delta: float = 0.2, ) -> RMetricIndicators ``` Calculate the R-metric (either R-HV or R-IGD) for a given solution set. solution_set : np.ndarray The set of solutions. np.ndarray A set of reference points.. np.ndarray, optional Weights for each objective. float, optional Region of interest for the metric calculation. RMetricIndicators An object containing the computed R-HV and R-IGD values. Source code in `desdeo/tools/indicators_unary.py` ``` def r_metric_indicator( solution_set: np.ndarray, ref_points: np.ndarray, w: np.ndarray = None, delta: float = 0.2 ) -> RMetricIndicators: """Calculate the R-metric (either R-HV or R-IGD) for a given solution set. Parameters: solution_set : np.ndarray The set of solutions. ref_points : np.ndarray A set of reference points.. w : np.ndarray, optional Weights for each objective. delta : float, optional Region of interest for the metric calculation. Returns: RMetricIndicators An object containing the computed R-HV and R-IGD values. """ # Calculate the Pareto front pareto_front = get_pareto_front(solution_set) rmetric = RMetric(problem=None, ref_points=ref_points, w=w, delta=delta, pf=pareto_front) r_igd, r_hv = rmetric.do(solution_set) return RMetricIndicators(r_hv=r_hv, r_igd=r_igd) ``` ### r_metric_indicators_batch ``` r_metric_indicators_batch( solution_set: dict[str, ndarray], ref_points: ndarray, w: ndarray = None, delta: float = 0.2, ) -> dict[str, RMetricIndicators] ``` Calculate the R-metrics (R-HV and R-IGD) for a batch of solution sets. Source code in `desdeo/tools/indicators_unary.py` ``` def r_metric_indicators_batch( solution_set: dict[str, np.ndarray], ref_points: np.ndarray, w: np.ndarray = None, delta: float = 0.2 ) -> dict[str, RMetricIndicators]: """Calculate the R-metrics (R-HV and R-IGD) for a batch of solution sets.""" inds = {} for set_name, sols in solution_set.items(): inds[set_name] = r_metric_indicator(sols, ref_points, w, delta) return inds ``` ### tchebycheff_utility ``` tchebycheff_utility( fx: ndarray, lambd: ndarray, z_star: ndarray, rho: float = 0.05, ) -> float ``` Calculates the augmented Tchebycheff utility of a solution. A *utility*, so it is the negated achievement scalarising value and **higher is better**. It is always negative, reaching zero only for a solution sitting on the ideal point. Source code in `desdeo/tools/indicators_unary.py` ``` def tchebycheff_utility(fx: np.ndarray, lambd: np.ndarray, z_star: np.ndarray, rho: float = 0.05) -> float: """Calculates the augmented Tchebycheff utility of a solution. A *utility*, so it is the negated achievement scalarising value and **higher is better**. It is always negative, reaching zero only for a solution sitting on the ideal point. """ diff = np.abs(z_star - fx) max_term = np.max(lambd * diff) sum_term = np.sum(diff) return -(max_term + rho * sum_term) ``` ## Binary indicators This module implements unary indicators that can be used to compare two solution sets. It assumes that the solution set has been normalized just that *some* ideal point (not necessarily the ideal point of the set) is the origin and *some* nadir point (not necessarily the nadir point of the set) is (1, 1, ..., 1). The normalized solution set is assumed to be inside the bounding box [0, 1]^k where k is the number of objectives. If these conditions are not met, the results of the indicators will not be meaningful. Additionally, the set may be assumed to only contain mutually non-dominated solutions, depending on the indicator. For now, we rely on pymoo for the implementation of many of the indicators. ### epsilon_component ``` epsilon_component( solution1: ndarray, solution2: ndarray ) -> float ``` Computes the additive epsilon-indicator between two solutions. Basically, returns the minimum amount by which the values in solution1 must be translated (minimization assumed) such that it (weakly) dominates solution2. If solution1 already dominates solution2, returns 0.0. Parameters: | Name | Type | Description | Default | | ----------- | --------- | --------------------------------------------------------------------------------- | ---------- | | `solution1` | `ndarray` | Should be an one-dimensional array, where each value is normalized between [0, 1] | *required* | | `solution2` | `ndarray` | Should be an one-dimensional array, where each value is normalized between [0, 1] | *required* | Returns: | Name | Type | Description | | ------- | ------- | ----------------------------------------------------- | | `float` | `float` | The maximum distance between the values in s1 and s2. | Source code in `desdeo/tools/indicators_binary.py` ``` @njit() def epsilon_component(solution1: np.ndarray, solution2: np.ndarray) -> float: """Computes the additive epsilon-indicator between two solutions. Basically, returns the minimum amount by which the values in solution1 must be translated (minimization assumed) such that it (weakly) dominates solution2. If solution1 already dominates solution2, returns 0.0. Args: solution1 (np.ndarray): Should be an one-dimensional array, where each value is normalized between [0, 1] solution2 (np.ndarray): Should be an one-dimensional array, where each value is normalized between [0, 1] Returns: float: The maximum distance between the values in s1 and s2. """ return max(0.0, max(solution1 - solution2)) # noqa: PLW3301 (numba @njit cannot unpack an array with *) ``` ### epsilon_indicator ``` epsilon_indicator( set1: ndarray, set2: ndarray, kind: Literal[ "additive", "multiplicative" ] = "additive", ) -> float ``` Computes the additive epsilon-indicator between two solution sets. Parameters: | Name | Type | Description | Default | | ------ | --------------------------------------- | ----------------------------------------------------------------------------------------- | ------------ | | `set1` | `ndarray` | Should be a two-dimensional array, where each row is a solution normalized between [0, 1] | *required* | | `set2` | `ndarray` | Should be a two-dimensional array, where each row is a solution normalized between [0, 1] | *required* | | `kind` | `Literal['additive', 'multiplicative']` | The kind of epsilon-indicator to compute. Defaults to "additive". | `'additive'` | Returns: | Name | Type | Description | | ------- | ------- | ------------------------------------------- | | `float` | `float` | the epsilon-indicator between the two sets. | Source code in `desdeo/tools/indicators_binary.py` ``` def epsilon_indicator( set1: np.ndarray, set2: np.ndarray, kind: Literal["additive", "multiplicative"] = "additive" ) -> float: """Computes the additive epsilon-indicator between two solution sets. Args: set1 (np.ndarray): Should be a two-dimensional array, where each row is a solution normalized between [0, 1] set2 (np.ndarray): Should be a two-dimensional array, where each row is a solution normalized between [0, 1] kind (Literal["additive", "multiplicative"]): The kind of epsilon-indicator to compute. Defaults to "additive". Returns: float: the epsilon-indicator between the two sets. """ if kind == "additive": return epsilon_additive(set1, ref=set2) if kind == "multiplicative": return epsilon_mult(set1, ref=set2) raise ValueError(f"Unknown kind: {kind}. Use 'additive' or 'multiplicative'.") ``` ### hv_component ``` hv_component( solution1: ndarray, solution2: ndarray, ref: float = 2.0 ) -> float ``` Computes the hypervolume contribution of solution1 with respect to solution2. Parameters: | Name | Type | Description | Default | | ----------- | --------- | --------------------------------------------------------------------------------- | ---------- | | `solution1` | `ndarray` | Should be an one-dimensional array, where each value is normalized between [0, 1] | *required* | | `solution2` | `ndarray` | Should be an one-dimensional array, where each value is normalized between [0, 1] | *required* | | `ref` | `float` | The reference point for the hypervolume calculation. Defaults to 2.0. | `2.0` | Returns: | Name | Type | Description | | ------- | ------- | -------------------------------------------------------------------- | | `float` | `float` | The hypervolume contribution of solution1 with respect to solution2. | Source code in `desdeo/tools/indicators_binary.py` ``` def hv_component(solution1: np.ndarray, solution2: np.ndarray, ref: float = 2.0) -> float: """Computes the hypervolume contribution of solution1 with respect to solution2. Args: solution1 (np.ndarray): Should be an one-dimensional array, where each value is normalized between [0, 1] solution2 (np.ndarray): Should be an one-dimensional array, where each value is normalized between [0, 1] ref (float): The reference point for the hypervolume calculation. Defaults to 2.0. Returns: float: The hypervolume contribution of solution1 with respect to solution2. """ if dominates(solution1, solution2): return np.prod(ref - solution2) - np.prod(ref - solution1) return hv(solution_set=np.array([solution1, solution2]), reference_point_component=ref) ``` ### self_epsilon ``` self_epsilon(solution_set: ndarray) -> np.ndarray ``` Computes the pairwise additive epsilon-indicator for a solution set. Parameters: | Name | Type | Description | Default | | -------------- | --------- | ------------------------------------------------------------------------------------------ | ---------- | | `solution_set` | `ndarray` | Should be a two-dimensional array, where each row is a solution normalized between [0, 1]. | *required* | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: A two-dimensional array where the entry at (i, j) is the additive epsilon-indicator between the i-th and j-th solution in the set. | Source code in `desdeo/tools/indicators_binary.py` ``` @njit() def self_epsilon(solution_set: np.ndarray) -> np.ndarray: """Computes the pairwise additive epsilon-indicator for a solution set. Args: solution_set (np.ndarray): Should be a two-dimensional array, where each row is a solution normalized between [0, 1]. Returns: np.ndarray: A two-dimensional array where the entry at (i, j) is the additive epsilon-indicator between the i-th and j-th solution in the set. """ n_solutions = solution_set.shape[0] eps_matrix = np.zeros((n_solutions, n_solutions), dtype=np.float64) for i in range(n_solutions): for j in range(n_solutions): eps_matrix[i, j] = epsilon_component(solution_set[i], solution_set[j]) return eps_matrix ``` ### self_hv ``` self_hv( solution_set: ndarray, ref: float = 2.0 ) -> np.ndarray ``` Computes the pairwise hypervolume contribution for a solution set. Parameters: | Name | Type | Description | Default | | -------------- | --------- | ------------------------------------------------------------------------------------------ | ---------- | | `solution_set` | `ndarray` | Should be a two-dimensional array, where each row is a solution normalized between [0, 1]. | *required* | | `ref` | `float` | The reference point for the hypervolume calculation. Defaults to 2.0. | `2.0` | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: A two-dimensional array where the entry at (i, j) is the hypervolume contribution of the i-th solution with respect to the j-th solution in the set. | Source code in `desdeo/tools/indicators_binary.py` ``` def self_hv(solution_set: np.ndarray, ref: float = 2.0) -> np.ndarray: """Computes the pairwise hypervolume contribution for a solution set. Args: solution_set (np.ndarray): Should be a two-dimensional array, where each row is a solution normalized between [0, 1]. ref (float): The reference point for the hypervolume calculation. Defaults to 2.0. Returns: np.ndarray: A two-dimensional array where the entry at (i, j) is the hypervolume contribution of the i-th solution with respect to the j-th solution in the set. """ n_solutions = solution_set.shape[0] hv_matrix = np.zeros((n_solutions, n_solutions), dtype=np.float64) for i in range(n_solutions): for j in range(n_solutions): hv_matrix[i, j] = hv_component(solution_set[i], solution_set[j], ref=ref) return hv_matrix ``` ## Reference vectors Reference vector generation for decomposition-based evolutionary methods. ### \_create_s_energy_cached ``` _create_s_energy_cached( number_of_objectives: int, number_of_vectors: int, seed: int, ) -> tuple ``` Build and cache one Riesz s-energy design, returned as a hashable tuple of rows. The construction is a seeded optimization costing roughly 0.5-3 s, and a benchmarking run rebuilds the same design once per algorithm instantiation. Caching on the three inputs that fully determine the result keeps that to once per process. Source code in `desdeo/tools/reference_vectors.py` ``` @lru_cache(maxsize=64) def _create_s_energy_cached(number_of_objectives: int, number_of_vectors: int, seed: int) -> tuple: """Build and cache one Riesz s-energy design, returned as a hashable tuple of rows. The construction is a seeded optimization costing roughly 0.5-3 s, and a benchmarking run rebuilds the same design once per algorithm instantiation. Caching on the three inputs that fully determine the result keeps that to once per process. """ vectors = np.asarray( get_reference_directions("energy", number_of_objectives, number_of_vectors, seed=seed), dtype=float, ) vectors = _ensure_axis_vectors(vectors) return tuple(map(tuple, vectors)) ``` ### \_ensure_axis_vectors ``` _ensure_axis_vectors(vectors: ndarray) -> np.ndarray ``` Guarantee that every axis direction is represented exactly, without changing the count. A decomposition-based algorithm only searches towards directions it has a vector for, so a set missing an axis never targets that objective's extreme and the corresponding edge of the front is simply not approximated. The current energy optimizer happens to pin the simplex vertices, but that is its implementation detail; enforcing it here makes the guarantee DESDEO's own. Any missing axis replaces whichever vector is closest to it, so the returned array keeps its shape and the substitution costs the least in spacing. Source code in `desdeo/tools/reference_vectors.py` ``` def _ensure_axis_vectors(vectors: np.ndarray) -> np.ndarray: """Guarantee that every axis direction is represented exactly, without changing the count. A decomposition-based algorithm only searches towards directions it has a vector for, so a set missing an axis never targets that objective's extreme and the corresponding edge of the front is simply not approximated. The current energy optimizer happens to pin the simplex vertices, but that is its implementation detail; enforcing it here makes the guarantee DESDEO's own. Any missing axis replaces whichever vector is closest to it, so the returned array keeps its shape and the substitution costs the least in spacing. """ number_of_objectives = vectors.shape[1] axes = np.eye(number_of_objectives) for axis_index in range(number_of_objectives): axis = axes[axis_index] if np.any(np.all(np.isclose(vectors, axis, atol=1e-9), axis=1)): continue closest = int(np.argmin(np.linalg.norm(vectors - axis, axis=1))) vectors[closest] = axis return vectors ``` ### add_edge_vectors ``` add_edge_vectors(values: ndarray) -> np.ndarray ``` Add edge (axis-aligned) vectors to the set of reference vectors. This ensures that each axis direction is represented in the set. Parameters: | Name | Type | Description | Default | | -------- | --------- | --------------------------- | ---------- | | `values` | `ndarray` | Array of reference vectors. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------------------------ | | `ndarray` | np.ndarray: Array of reference vectors with edge vectors added and normalized. | Source code in `desdeo/tools/reference_vectors.py` ``` def add_edge_vectors(values: np.ndarray) -> np.ndarray: """Add edge (axis-aligned) vectors to the set of reference vectors. This ensures that each axis direction is represented in the set. Args: values (np.ndarray): Array of reference vectors. Returns: np.ndarray: Array of reference vectors with edge vectors added and normalized. """ edge_vectors = np.eye(values.shape[1]) values = np.vstack([values, edge_vectors]) return normalize(values) ``` ### approx_lattice_resolution ``` approx_lattice_resolution( number_of_vectors: int, num_dims: int ) -> int ``` Approximate the lattice resolution based on the number of vectors and dimensions. Parameters: | Name | Type | Description | Default | | ------------------- | ----- | ------------------------------------ | ---------- | | `number_of_vectors` | `int` | Desired number of reference vectors. | *required* | | `num_dims` | `int` | Number of objectives (dimensions). | *required* | Returns: | Name | Type | Description | | ----- | ----- | -------------------------------------------------------------------------------------- | | `int` | `int` | The smallest lattice resolution that produces more than the desired number of vectors. | Source code in `desdeo/tools/reference_vectors.py` ``` def approx_lattice_resolution(number_of_vectors: int, num_dims: int) -> int: """Approximate the lattice resolution based on the number of vectors and dimensions. Args: number_of_vectors (int): Desired number of reference vectors. num_dims (int): Number of objectives (dimensions). Returns: int: The smallest lattice resolution that produces more than the desired number of vectors. """ temp_lattice_resolution = 0 while True: temp_lattice_resolution += 1 temp_number_of_vectors = comb( temp_lattice_resolution + num_dims - 1, num_dims - 1, exact=True, ) if temp_number_of_vectors > number_of_vectors: break return temp_lattice_resolution - 1 ``` ### create_s_energy ``` create_s_energy( number_of_objectives: int, number_of_vectors: int, seed: int = 0, ) -> np.ndarray ``` Create reference vectors by minimizing the Riesz s-energy over the unit simplex. Unlike the simplex lattice design, this produces *exactly* `number_of_vectors` vectors for any combination of count and dimension. The lattice can only realize the binomial counts `C(H + m - 1, m - 1)`, so it cannot hit an arbitrary target: at `m = 8` the reachable counts jump 36, 120, 330, and asking for 100 vectors yields 36. That matters because the population size of a decomposition-based algorithm is its reference vector count. Every axis direction is guaranteed to be present exactly, so each objective's extreme is always a search target; see `_ensure_axis_vectors`. Parameters: | Name | Type | Description | Default | | ---------------------- | ----- | --------------------------------------------------------------------- | ---------- | | `number_of_objectives` | `int` | Number of objectives (dimensions). | *required* | | `number_of_vectors` | `int` | Exact number of reference vectors to produce. | *required* | | `seed` | `int` | Seed for the energy optimization, which is stochastic. Defaults to 0. | `0` | Returns: | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: Array of reference vectors, shape (number_of_vectors, number_of_objectives), lying on the unit simplex (rows sum to one), including the number_of_objectives axis vectors. | Raises: | Type | Description | | ------------ | --------------------------------------------------------------------------------------------------- | | `ValueError` | If number_of_vectors is smaller than number_of_objectives, which cannot cover the simplex vertices. | References Blank, J., Deb, K., Dhebar, Y., Bandaru, S., & Seada, H. (2021). Generating Well-Spaced Points on a Unit Simplex for Evolutionary Many-Objective Optimization. IEEE Transactions on Evolutionary Computation, 25(1), 48-60. https://doi.org/10.1109/TEVC.2020.2992387 Source code in `desdeo/tools/reference_vectors.py` ``` def create_s_energy( number_of_objectives: int, number_of_vectors: int, seed: int = 0, ) -> np.ndarray: """Create reference vectors by minimizing the Riesz s-energy over the unit simplex. Unlike the simplex lattice design, this produces *exactly* `number_of_vectors` vectors for any combination of count and dimension. The lattice can only realize the binomial counts `C(H + m - 1, m - 1)`, so it cannot hit an arbitrary target: at `m = 8` the reachable counts jump 36, 120, 330, and asking for 100 vectors yields 36. That matters because the population size of a decomposition-based algorithm is its reference vector count. Every axis direction is guaranteed to be present exactly, so each objective's extreme is always a search target; see `_ensure_axis_vectors`. Args: number_of_objectives (int): Number of objectives (dimensions). number_of_vectors (int): Exact number of reference vectors to produce. seed (int, optional): Seed for the energy optimization, which is stochastic. Defaults to 0. Returns: np.ndarray: Array of reference vectors, shape `(number_of_vectors, number_of_objectives)`, lying on the unit simplex (rows sum to one), including the `number_of_objectives` axis vectors. Raises: ValueError: If `number_of_vectors` is smaller than `number_of_objectives`, which cannot cover the simplex vertices. References: Blank, J., Deb, K., Dhebar, Y., Bandaru, S., & Seada, H. (2021). Generating Well-Spaced Points on a Unit Simplex for Evolutionary Many-Objective Optimization. IEEE Transactions on Evolutionary Computation, 25(1), 48-60. https://doi.org/10.1109/TEVC.2020.2992387 """ if number_of_vectors < number_of_objectives: raise ValueError( f"Cannot place {number_of_vectors} reference vectors in {number_of_objectives} dimensions: " f"at least one vector per objective is needed to cover the simplex vertices." ) return np.array(_create_s_energy_cached(number_of_objectives, number_of_vectors, seed), dtype=float) ``` ### create_simplex ``` create_simplex( number_of_objectives: int, lattice_resolution: int | None = None, number_of_vectors: int | None = None, ) -> np.ndarray ``` Create reference vectors using the simplex lattice design. Parameters: | Name | Type | Description | Default | | ---------------------- | ----- | ------------------------------------------------------------------------------ | ---------- | | `number_of_objectives` | `int` | Number of objectives (dimensions). | *required* | | `lattice_resolution` | `int` | Lattice resolution to use. If None, will be determined from number_of_vectors. | `None` | | `number_of_vectors` | `int` | Desired number of reference vectors. Used if lattice_resolution is None. | `None` | Returns: | Type | Description | | --------- | -------------------------------------------------- | | `ndarray` | np.ndarray: Array of normalized reference vectors. | Raises: | Type | Description | | ------------ | ---------------------------------------------------------- | | `ValueError` | If both lattice_resolution and number_of_vectors are None. | Source code in `desdeo/tools/reference_vectors.py` ``` def create_simplex( number_of_objectives: int, lattice_resolution: int | None = None, number_of_vectors: int | None = None, ) -> np.ndarray: """Create reference vectors using the simplex lattice design. Args: number_of_objectives (int): Number of objectives (dimensions). lattice_resolution (int, optional): Lattice resolution to use. If None, will be determined from number_of_vectors. number_of_vectors (int, optional): Desired number of reference vectors. Used if lattice_resolution is None. Returns: np.ndarray: Array of normalized reference vectors. Raises: ValueError: If both lattice_resolution and number_of_vectors are None. """ if lattice_resolution is None and number_of_vectors is None: raise ValueError("Either lattice resolution or number of vectors must be specified.") if lattice_resolution is None: lattice_resolution = approx_lattice_resolution(number_of_vectors, number_of_objectives) number_of_vectors = comb( lattice_resolution + number_of_objectives - 1, number_of_objectives - 1, exact=True, ) temp1 = range(1, number_of_objectives + lattice_resolution) temp1 = np.array(list(combinations(temp1, number_of_objectives - 1))) temp2 = np.array([range(number_of_objectives - 1)] * number_of_vectors) temp = temp1 - temp2 - 1 weight = np.zeros((number_of_vectors, number_of_objectives), dtype=int) weight[:, 0] = temp[:, 0] for i in range(1, number_of_objectives - 1): weight[:, i] = temp[:, i] - temp[:, i - 1] weight[:, -1] = lattice_resolution - temp[:, -1] values = weight / lattice_resolution return normalize(values) ``` ### householder ``` householder(vector) ``` Return reflection matrix via householder transformation. Source code in `desdeo/tools/reference_vectors.py` ``` def householder(vector): """Return reflection matrix via householder transformation.""" identity_mat = np.eye(len(vector)) v = vector[np.newaxis] denominator = np.matmul(v, v.T) numerator = np.matmul(v.T, v) return identity_mat - (2 * numerator / denominator) ``` ### neighbouring_angles ``` neighbouring_angles(values: ndarray) -> np.ndarray ``` Calculate the angles to the nearest neighbor for each reference vector. Parameters: | Name | Type | Description | Default | | -------- | --------- | -------------------------------------- | ---------- | | `values` | `ndarray` | Array of normalized reference vectors. | *required* | Returns: | Type | Description | | --------- | --------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: Array of angles (in radians) to the nearest neighbor for each vector. | Source code in `desdeo/tools/reference_vectors.py` ``` def neighbouring_angles(values: np.ndarray) -> np.ndarray: """Calculate the angles to the nearest neighbor for each reference vector. Args: values (np.ndarray): Array of normalized reference vectors. Returns: np.ndarray: Array of angles (in radians) to the nearest neighbor for each vector. """ cosvv = np.dot(values, values.transpose()) cosvv.sort(axis=1) cosvv = np.flip(cosvv, 1) cosvv[cosvv > 1] = 1 return np.arccos(cosvv[:, 1]) ``` ### normalize ``` normalize(values: ndarray) -> np.ndarray ``` Normalize a set of vectors to unit length (project onto the unit hypersphere). Parameters: | Name | Type | Description | Default | | -------- | --------- | ------------------------------ | ---------- | | `values` | `ndarray` | Array of vectors to normalize. | *required* | Returns: | Type | Description | | --------- | ------------------------------- | | `ndarray` | np.ndarray: Normalized vectors. | Source code in `desdeo/tools/reference_vectors.py` ``` def normalize(values: np.ndarray) -> np.ndarray: """Normalize a set of vectors to unit length (project onto the unit hypersphere). Args: values (np.ndarray): Array of vectors to normalize. Returns: np.ndarray: Normalized vectors. """ norm_2 = np.linalg.norm(values, axis=1).reshape(-1, 1) norm_2[norm_2 == 0] = np.finfo(float).eps return np.divide(values, norm_2) ``` ### rotate ``` rotate(initial_vector, rotated_vector, other_vectors) ``` Calculate the rotation matrix that rotates the initial_vector to the rotated_vector. Apply that rotation on other_vectors and return. Uses Householder reflections twice to achieve this. Source code in `desdeo/tools/reference_vectors.py` ``` def rotate(initial_vector, rotated_vector, other_vectors): """Calculate the rotation matrix that rotates the initial_vector to the rotated_vector. Apply that rotation on other_vectors and return. Uses Householder reflections twice to achieve this. """ init_vec_norm = normalize(initial_vector) rot_vec_norm = normalize(np.asarray(rotated_vector)) middle_vec_norm = normalize(init_vec_norm + rot_vec_norm) first_reflector = init_vec_norm - middle_vec_norm second_reflector = middle_vec_norm - rot_vec_norm Q1 = householder(first_reflector) # noqa: N806 Q2 = householder(second_reflector) # noqa: N806 reflection_matrix = np.matmul(Q2, Q1) return np.matmul(other_vectors, np.transpose(reflection_matrix)) ``` ### rotate_toward ``` rotate_toward( initial_vector, final_vector, other_vectors, degrees: float = 5, ) ``` Rotate other_vectors (with the centre at initial_vector) towards final_vector by an angle degrees. ##### Parameters initial_vector : np.ndarray Centre of the vectors to be rotated. final_vector : np.ndarray The final position of the center of other_vectors. other_vectors : np.ndarray The array of vectors to be rotated degrees : float, optional The amount of rotation (the default is 5) ##### Returns: rotated_vectors : np.ndarray The rotated vectors reached: bool True if final_vector has been reached Source code in `desdeo/tools/reference_vectors.py` ``` def rotate_toward(initial_vector, final_vector, other_vectors, degrees: float = 5): """Rotate other_vectors (with the centre at initial_vector) towards final_vector by an angle degrees. Parameters ---------- initial_vector : np.ndarray Centre of the vectors to be rotated. final_vector : np.ndarray The final position of the center of other_vectors. other_vectors : np.ndarray The array of vectors to be rotated degrees : float, optional The amount of rotation (the default is 5) Returns: ------- rotated_vectors : np.ndarray The rotated vectors reached: bool True if final_vector has been reached """ final_vector = normalize(final_vector) initial_vector = normalize(initial_vector) cos_phi = np.dot(initial_vector, final_vector) theta = degrees * np.pi / 180 cos_theta = np.cos(theta) phi = np.arccos(cos_phi) if phi < theta: return (rotate(initial_vector, final_vector, other_vectors), True) cos_phi_theta = np.cos(phi - theta) A = np.asarray([[cos_phi, 1], [1, cos_phi]]) # noqa: N806 B = np.asarray([cos_phi_theta, cos_theta]) # noqa: N806 x = np.linalg.solve(A, B) rotated_vector = x[0] * initial_vector + x[1] * final_vector return (rotate(initial_vector, rotated_vector, other_vectors), False) ``` ### shear ``` shear(vectors, degrees: float = 5) ``` Shear a set of vectors lying on the plane z=0 towards the z-axis. The resulting vectors are'degrees' angle away from the z axis. ##### Parameters vectors : numpy.ndarray The final element of each vector should be zero. degrees : float, optional The angle that the resultant vectors make with the z axis. Unit is radians. (the default is 5) Source code in `desdeo/tools/reference_vectors.py` ``` def shear(vectors, degrees: float = 5): """Shear a set of vectors lying on the plane z=0 towards the z-axis. The resulting vectors are'degrees' angle away from the z axis. Parameters ---------- vectors : numpy.ndarray The final element of each vector should be zero. degrees : float, optional The angle that the resultant vectors make with the z axis. Unit is radians. (the default is 5) """ angle = degrees * np.pi / 180 m = 1 / np.tan(angle) norm = np.linalg.norm(vectors, axis=1) vectors[:, -1] += norm * m return normalize(vectors) ``` ## Reference point generation Generate reference points for the IPA algorithm. ### generate_points ``` generate_points( num_points: int, num_dims: int ) -> tuple[np.ndarray, np.ndarray] ``` Generate reference points for the IPA algorithm. Creates a (large) number of reference points on a plane perpendicular to the largest space diagonal of the unit hypercube in the num_dims-dimensional space. First, the vertices of the unit hypercube are generated. Then, the vertices are projected onto the plane perpendicular to the largest space diagonal (vertex first parallel projection) and rotated such that the plane is perpendular to one of the axes, making all objective values zero. A convex hull is then constructed from the projected vertices, and a bounding box is constructed around the convex hull. Finally, points are generated uniformly within the bounding box until num_points points are generated *inside* the convex hull. Note that the number of dimensions must be at least 2. Also, the number of dimensions of the reference points is one less than the number of dimensions of the objective space. This is because the reference points are generated on the projected plane. Parameters: | Name | Type | Description | Default | | ------------ | ----- | ---------------------------------------------------------------------------------- | ---------- | | `num_points` | `int` | The number of reference points to generate. | *required* | | `num_dims` | `int` | The number of dimensions of the space in which the reference points are generated. | *required* | Returns: | Type | Description | | ------------------------- | -------------------------------------------------------------------- | | `tuple[ndarray, ndarray]` | np.ndarray: A (num_points) x (num_dims-1) array of reference points. | Source code in `desdeo/tools/generateReferencePoints.py` ``` def generate_points( num_points: int, num_dims: int ) -> tuple[ np.ndarray, np.ndarray, ]: """Generate reference points for the IPA algorithm. Creates a (large) number of reference points on a plane perpendicular to the largest space diagonal of the unit hypercube in the num_dims-dimensional space. First, the vertices of the unit hypercube are generated. Then, the vertices are projected onto the plane perpendicular to the largest space diagonal (vertex first parallel projection) and rotated such that the plane is perpendular to one of the axes, making all objective values zero. A convex hull is then constructed from the projected vertices, and a bounding box is constructed around the convex hull. Finally, points are generated uniformly within the bounding box until num_points points are generated _inside_ the convex hull. Note that the number of dimensions must be at least 2. Also, the number of dimensions of the reference points is one less than the number of dimensions of the objective space. This is because the reference points are generated on the projected plane. Args: num_points (int): The number of reference points to generate. num_dims (int): The number of dimensions of the space in which the reference points are generated. Returns: np.ndarray: A (num_points) x (num_dims-1) array of reference points. """ bounding_box, a, b, _ = get_reference_hull(num_dims) # bounding_box, A, b, hull points = numba_random_gen(num_points, bounding_box, a, b) # Project vertices onto plane perpendicular to largest space diagonal points_rotated = rotate_out(points) return points, points_rotated ``` ### get_hull_equations ``` get_hull_equations( hull: ConvexHull, ) -> tuple[np.ndarray, np.ndarray] ``` Get the equations of the hyperplanes defining the convex hull. Parameters: | Name | Type | Description | Default | | ------ | ------------ | -------------- | ---------- | | `hull` | `ConvexHull` | A convex hull. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: A (num_dims-1) x num_hyperplanes array of the coefficients of the hyperplanes defining the convex hull. | | `ndarray` | np.ndarray: A (num_hyperplanes) array of the constants of the hyperplanes defining the convex hull. | Source code in `desdeo/tools/generateReferencePoints.py` ``` def get_hull_equations(hull: ConvexHull) -> tuple[np.ndarray, np.ndarray]: """Get the equations of the hyperplanes defining the convex hull. Args: hull (scipy.spatial.ConvexHull): A convex hull. Returns: np.ndarray: A (num_dims-1) x num_hyperplanes array of the coefficients of the hyperplanes defining the convex hull. np.ndarray: A (num_hyperplanes) array of the constants of the hyperplanes defining the convex hull. """ return np.ascontiguousarray(hull.equations[:, :-1].T), np.ascontiguousarray(hull.equations[:, -1].T) ``` ### get_reference_hull ``` get_reference_hull( num_dims, ) -> tuple[np.ndarray, np.ndarray, np.ndarray, ConvexHull] ``` Get the convex hull of the valid reference points for IPA. This algorithm generates the vertices of the unit hypercube in the (num_dims)-dimensional space. Then, the vertices are projected onto the plane perpendicular to the largest space diagonal (vertex first parallel projection) and rotated such that the plane is perpendular to one of the axes. Then, the points are are flattened to (num_dims-1)-dimensional space. A convex hull is then constructed from the projected vertices, and a bounding box is constructed around the convex hull. Parameters: | Name | Type | Description | Default | | ---------- | ----- | ---------------------------------------------------------------------------------- | ---------- | | `num_dims` | `int` | The number of dimensions of the space in which the reference points are generated. | *required* | Returns: | Type | Description | | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: A (2) x (num_dims-1) array of the bounding box. Reference points are guaranteed to be within this box. However, not all points within this box are valid reference points. | | `ndarray` | np.ndarray: A (num_dims-1) x (num_dims-1) array of the coefficients of the hyperplanes defining the convex hull of the bounds of the reference points. A point is a valid reference point if it lies within the convex hull. | | `ndarray` | np.ndarray: A (num_dims-1) array of the constants of the hyperplanes defining the convex hull. See above. | | `ConvexHull` | scipy.spatial.ConvexHull: The convex hull of the projected vertices/valid reference points. | Source code in `desdeo/tools/generateReferencePoints.py` ``` def get_reference_hull(num_dims) -> tuple[np.ndarray, np.ndarray, np.ndarray, ConvexHull]: """Get the convex hull of the valid reference points for IPA. This algorithm generates the vertices of the unit hypercube in the (num_dims)-dimensional space. Then, the vertices are projected onto the plane perpendicular to the largest space diagonal (vertex first parallel projection) and rotated such that the plane is perpendular to one of the axes. Then, the points are are flattened to (num_dims-1)-dimensional space. A convex hull is then constructed from the projected vertices, and a bounding box is constructed around the convex hull. Args: num_dims (int): The number of dimensions of the space in which the reference points are generated. Returns: np.ndarray: A (2) x (num_dims-1) array of the bounding box. Reference points are guaranteed to be within this box. However, not all points within this box are valid reference points. np.ndarray: A (num_dims-1) x (num_dims-1) array of the coefficients of the hyperplanes defining the convex hull of the bounds of the reference points. A point is a valid reference point if it lies within the convex hull. np.ndarray: A (num_dims-1) array of the constants of the hyperplanes defining the convex hull. See above. scipy.spatial.ConvexHull: The convex hull of the projected vertices/valid reference points. """ vertices = np.array(list(product([0, 1], repeat=num_dims))) # Project vertices onto plane perpendicular to largest space diagonal, rotate to make one of the objectives zero. # Then flatten to (num_dims-1) dimensions. rotated_vertices = rotate_in(vertices) bounding_box = np.array([np.min(rotated_vertices, axis=0), np.max(rotated_vertices, axis=0)]) hull = ConvexHull(rotated_vertices) a, b = get_hull_equations(hull) # A, b return bounding_box, a, b, hull ``` ### householder ``` householder(vector) ``` Return reflection matrix via householder transformation. Source code in `desdeo/tools/generateReferencePoints.py` ``` def householder(vector): """Return reflection matrix via householder transformation.""" identity_mat = np.eye(len(vector)) v = vector[np.newaxis] denominator = np.matmul(v, v.T) numerator = np.matmul(v.T, v) return identity_mat - (2 * numerator / denominator) ``` ### normalize ``` normalize(vectors) ``` Normalize a set of vectors. The length of the returned vectors will be 1. ##### Parameters vectors : np.ndarray Set of vectors of any length, except zero. Source code in `desdeo/tools/generateReferencePoints.py` ``` def normalize(vectors): """Normalize a set of vectors. The length of the returned vectors will be 1. Parameters ---------- vectors : np.ndarray Set of vectors of any length, except zero. """ if len(np.asarray(vectors).shape) == 1: return vectors / np.linalg.norm(vectors) norm = np.linalg.norm(vectors, axis=1) return vectors / norm[:, np.newaxis] ``` ### numba_random_gen ``` numba_random_gen( num_points: int, bounding_box: ndarray, a: ndarray, b: ndarray, ) -> np.ndarray ``` Generates num_points random points within the convex hull defined by A and b. Parameters: | Name | Type | Description | Default | | -------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `num_points` | `int` | The number of points to generate. | *required* | | `bounding_box` | `ndarray` | A (2) x (num_objs - 1) array defining the bounding box within which to generate points initially. | *required* | | `a` | `ndarray` | A (num_hyperplanes) x (num_objs - 1) array of the coefficients of the hyperplanes defining the convex hull. Basically the first num_objs - 1 columns of hull.equations. | *required* | | `b` | `ndarray` | A (num_hyperplanes) array of the constants of the hyperplanes defining the convex hull. Basically the last column of hull.equations. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------ | | `ndarray` | np.ndarray: A (num_points) x (num_objs - 1) array of points within the convex hull defined by A and b. | Source code in `desdeo/tools/generateReferencePoints.py` ``` @njit() def numba_random_gen(num_points: int, bounding_box: np.ndarray, a: np.ndarray, b: np.ndarray) -> np.ndarray: """Generates num_points random points within the convex hull defined by A and b. Args: num_points (int): The number of points to generate. bounding_box (np.ndarray): A (2) x (num_objs - 1) array defining the bounding box within which to generate points initially. a (np.ndarray): A (num_hyperplanes) x (num_objs - 1) array of the coefficients of the hyperplanes defining the convex hull. Basically the first num_objs - 1 columns of hull.equations. b (np.ndarray): A (num_hyperplanes) array of the constants of the hyperplanes defining the convex hull. Basically the last column of hull.equations. Returns: np.ndarray: A (num_points) x (num_objs - 1) array of points within the convex hull defined by A and b. """ num_dims_ = bounding_box.shape[1] points = np.zeros((num_points, num_dims_)) eps = np.finfo(np.float32).eps counter = 0 while counter < num_points: point = np.zeros(num_dims_) for i in range(num_dims_): # Generate a random point within the bounding box. # NOTE: numba's nopython mode does not support the np.random.Generator # API, so the legacy np.random.uniform must be used here. point[i] = np.random.uniform(bounding_box[0, i], bounding_box[1, i]) # noqa: NPY002 if np.all(point @ a + b < eps): # point @ A + b # If the point is inside the convex hull, add it to the list of points points[counter] = point counter += 1 return points ``` ### rotate ``` rotate(initial_vector, rotated_vector, other_vectors) ``` Calculate the rotation matrix that rotates the initial_vector... ...to the rotated_vector. Apply that rotation on other_vectors and return. Uses Householder reflections twice to achieve this. Source code in `desdeo/tools/generateReferencePoints.py` ``` def rotate(initial_vector, rotated_vector, other_vectors): """Calculate the rotation matrix that rotates the initial_vector... ...to the rotated_vector. Apply that rotation on other_vectors and return. Uses Householder reflections twice to achieve this. """ init_vec_norm = normalize(initial_vector) rot_vec_norm = normalize(np.asarray(rotated_vector)) middle_vec_norm = normalize(init_vec_norm + rot_vec_norm) first_reflector = init_vec_norm - middle_vec_norm second_reflector = middle_vec_norm - rot_vec_norm q1 = householder(first_reflector) q2 = householder(second_reflector) reflection_matrix = np.matmul(q2, q1) return np.matmul(other_vectors, np.transpose(reflection_matrix)) ``` ### rotate_in ``` rotate_in(vertices: ndarray) -> np.ndarray ``` Project the vertices to a lower dimensional space. First, the vertices are rotated such that the plane perpendicular to the ideal-nadir line becomes perpendicular to one of the axes. Essentially, (1,1,...,1) is rotated to (0,0,...,0,1). Then, the last dimension is dropped. Parameters: | Name | Type | Description | Default | | ---------- | --------- | ----------------------------- | ---------- | | `vertices` | `ndarray` | The vertices to be projected. | *required* | Returns: | Type | Description | | --------- | ----------------------------------- | | `ndarray` | np.ndarray: The projected vertices. | Source code in `desdeo/tools/generateReferencePoints.py` ``` def rotate_in(vertices: np.ndarray) -> np.ndarray: """Project the vertices to a lower dimensional space. First, the vertices are rotated such that the plane perpendicular to the ideal-nadir line becomes perpendicular to one of the axes. Essentially, (1,1,...,1) is rotated to (0,0,...,0,1). Then, the last dimension is dropped. Args: vertices (np.ndarray): The vertices to be projected. Returns: np.ndarray: The projected vertices. """ num_dims = len(vertices[0]) rotated_vertices = rotate([1] * num_dims, ([0] * (num_dims - 1) + [1]), vertices) return rotated_vertices[:, :-1] ``` ### rotate_out ``` rotate_out(points: ndarray) -> np.ndarray ``` Undo the `rotate_in` operation. Parameters: | Name | Type | Description | Default | | -------- | --------- | -------------------------------- | ---------- | | `points` | `ndarray` | The points to be projected back. | *required* | Returns: | Type | Description | | --------- | --------------------------------- | | `ndarray` | np.ndarray: The projected points. | Source code in `desdeo/tools/generateReferencePoints.py` ``` def rotate_out(points: np.ndarray) -> np.ndarray: """Undo the `rotate_in` operation. Args: points (np.ndarray): The points to be projected back. Returns: np.ndarray: The projected points. """ points = np.atleast_2d(points) num_dims = points.shape[1] points_rotated = np.hstack((points, np.ones((len(points), 1)))) points_rotated = rotate(([0] * (num_dims) + [1]), [1] * (num_dims + 1), points_rotated) # Move (along nadir-ideal direction) the plane of these points such that it passes through nadir return points_rotated + 1 - 1 / np.sqrt(num_dims + 1) ``` ## Non-dominated sorting This module contains functions for non-dominated sorting of solutions. ### constrained_fronts ``` constrained_fronts( targets: ndarray, violations: ndarray | None ) -> np.ndarray ``` Rank a population into fronts under the constrained domination of Deb et al. (2002). Constrained domination never compares a feasible solution with an infeasible one on objectives, so the two groups can be ranked separately and concatenated instead of a dominance relation being redefined. The feasible group gets the ordinary non-dominated sort; the infeasible group is stratified by total violation, one front per distinct value, which is what "the one with the smaller violation wins" means as a ranking. Without constraints this is the ordinary sort. Parameters: | Name | Type | Description | Default | | ------------ | --------- | ---------------------------------------------- | ------------------------------------------------------------------------- | | `targets` | `ndarray` | the minimized objective vectors, shape (n, m). | *required* | | `violations` | \`ndarray | None\` | total constraint violation per row, or None for an unconstrained problem. | Returns: | Type | Description | | --------- | ----------------------------------------------------------------------- | | `ndarray` | np.ndarray: boolean front masks, shape (n_fronts, n), best front first. | Source code in `desdeo/tools/non_dominated_sorting.py` ``` def constrained_fronts(targets: np.ndarray, violations: np.ndarray | None) -> np.ndarray: """Rank a population into fronts under the constrained domination of Deb et al. (2002). Constrained domination never compares a feasible solution with an infeasible one on objectives, so the two groups can be ranked separately and concatenated instead of a dominance relation being redefined. The feasible group gets the ordinary non-dominated sort; the infeasible group is stratified by total violation, one front per distinct value, which is what "the one with the smaller violation wins" means as a ranking. Without constraints this is the ordinary sort. Args: targets (np.ndarray): the minimized objective vectors, shape `(n, m)`. violations (np.ndarray | None): total constraint violation per row, or None for an unconstrained problem. Returns: np.ndarray: boolean front masks, shape `(n_fronts, n)`, best front first. """ if violations is None: return fast_non_dominated_sort(targets) feasible = np.flatnonzero(violations <= 0) infeasible = np.flatnonzero(violations > 0) fronts = [] if feasible.size > 0: for front in fast_non_dominated_sort(targets[feasible]): row = np.zeros(len(targets), dtype=np.bool_) row[feasible[front]] = True fronts.append(row) for violation in np.unique(violations[infeasible]): row = np.zeros(len(targets), dtype=np.bool_) row[infeasible[violations[infeasible] == violation]] = True fronts.append(row) return np.array(fronts) ``` ### dominance_matrix ``` dominance_matrix(data: ndarray) -> np.ndarray ``` Finds the pairwise dominance relations in a population of solutions. Parameters: | Name | Type | Description | Default | | ------ | --------- | -------------------------------------------------------------- | ---------- | | `data` | `ndarray` | 2-D array of solutions, with each row being a single solution. | *required* | Returns: | Type | Description | | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: n x n boolean array, where n is the number of solutions. The element (i, j) is true if solution i dominates solution j. False otherwise. | Source code in `desdeo/tools/non_dominated_sorting.py` ``` @njit() def dominance_matrix(data: np.ndarray) -> np.ndarray: """Finds the pairwise dominance relations in a population of solutions. Args: data (np.ndarray): 2-D array of solutions, with each row being a single solution. Returns: np.ndarray: n x n boolean array, where n is the number of solutions. The element (i, j) is true if solution i dominates solution j. False otherwise. """ num_solutions = len(data) matrix = np.zeros((num_solutions, num_solutions), dtype=np.bool_) for i in range(num_solutions): for j in range(i + 1, num_solutions): if dominates(data[i], data[j]): matrix[i, j] = True elif dominates(data[j], data[i]): matrix[j, i] = True return matrix ``` ### dominates ``` dominates(x: ndarray, y: ndarray) -> bool ``` Returns true if x dominates y. Parameters: | Name | Type | Description | Default | | ---- | --------- | -------------------------------------------------- | ---------- | | `x` | `ndarray` | First solution. Should be a 1-D array of numerics. | *required* | | `y` | `ndarray` | Second solution. Should be the same shape as x. | *required* | Returns: | Name | Type | Description | | ------ | ------ | --------------------------------------- | | `bool` | `bool` | True if x dominates y, false otherwise. | Source code in `desdeo/tools/non_dominated_sorting.py` ``` @njit() def dominates(x: np.ndarray, y: np.ndarray) -> bool: """Returns true if x dominates y. Args: x (np.ndarray): First solution. Should be a 1-D array of numerics. y (np.ndarray): Second solution. Should be the same shape as x. Returns: bool: True if x dominates y, false otherwise. """ dom = False for i in range(len(x)): if x[i] > y[i]: return False if x[i] < y[i]: dom = True return dom ``` ### fast_non_dominated_sort ``` fast_non_dominated_sort(data: ndarray) -> np.ndarray ``` Conduct fast non-dominated sorting on a population of solutions. Parameters: | Name | Type | Description | Default | | ------ | --------- | -------------------------------------------------------------- | ---------- | | `data` | `ndarray` | 2-D array of solutions, with each row being a single solution. | *required* | Returns: | Type | Description | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: n x f boolean array. n is the number of solutions, f is the number of fronts. The value of an array element is true if the corresponding solution id (column) belongs in the corresponding front (row). | Source code in `desdeo/tools/non_dominated_sorting.py` ``` @njit() def fast_non_dominated_sort(data: np.ndarray) -> np.ndarray: """Conduct fast non-dominated sorting on a population of solutions. Args: data (np.ndarray): 2-D array of solutions, with each row being a single solution. Returns: np.ndarray: n x f boolean array. n is the number of solutions, f is the number of fronts. The value of an array element is true if the corresponding solution id (column) belongs in the corresponding front (row). """ num_solutions = len(data) indices = np.arange(num_solutions) taken = np.zeros(num_solutions, dtype=np.bool_) fronts = np.zeros((num_solutions, num_solutions), dtype=np.bool_) for i in indices: current_front = non_dominated(data[~taken]) current_front_all = np.zeros(num_solutions, dtype=np.bool_) current_front_all[~taken] = current_front fronts[i] = current_front_all taken = taken + fronts[i] if taken.all(): # if all the solutions have been sorted, stop break return fronts[: i + 1] ``` ### fast_non_dominated_sort_indices ``` fast_non_dominated_sort_indices( data: ndarray, ) -> list[list[int]] ``` Conduct fast non-dominated sorting on a population of solutions. This function returns identical results as `fast_non_dominated_sort`, but in a different format. This function returns an array of solution indices for each front, packed in a list. Parameters: | Name | Type | Description | Default | | ------ | --------- | -------------------------------------------------------------- | ---------- | | `data` | `ndarray` | 2-D array of solutions, with each row being a single solution. | *required* | Returns: | Type | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `list[list[int]]` | list\[list[int]\]: A list with f elements where f is the number of fronts in the data, arranged in ascending order. Each element is a list of the indices of solutions belonging to the corresponding front. | Source code in `desdeo/tools/non_dominated_sorting.py` ``` def fast_non_dominated_sort_indices(data: np.ndarray) -> list[list[int]]: """Conduct fast non-dominated sorting on a population of solutions. This function returns identical results as `fast_non_dominated_sort`, but in a different format. This function returns an array of solution indices for each front, packed in a list. Args: data (np.ndarray): 2-D array of solutions, with each row being a single solution. Returns: list[list[int]]: A list with f elements where f is the number of fronts in the data, arranged in ascending order. Each element is a list of the indices of solutions belonging to the corresponding front. """ fronts = fast_non_dominated_sort(data) return [np.where(fronts[i])[0].tolist() for i in range(len(fronts))] ``` ### non_dominated ``` non_dominated(data: ndarray) -> np.ndarray ``` Finds the non-dominated front from a population of solutions. Parameters: | Name | Type | Description | Default | | ------ | --------- | -------------------------------------------------------------- | ---------- | | `data` | `ndarray` | 2-D array of solutions, with each row being a single solution. | *required* | Returns: | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: Boolean array of same length as number of solutions (rows). The value is true if corresponding solution is non-dominated. False otherwise | Source code in `desdeo/tools/non_dominated_sorting.py` ``` @njit() def non_dominated(data: np.ndarray) -> np.ndarray: """Finds the non-dominated front from a population of solutions. Args: data (np.ndarray): 2-D array of solutions, with each row being a single solution. Returns: np.ndarray: Boolean array of same length as number of solutions (rows). The value is true if corresponding solution is non-dominated. False otherwise """ num_solutions = len(data) index = np.zeros(num_solutions, dtype=np.bool_) index[0] = True for i in range(1, num_solutions): index[i] = True for j in range(i): if not index[j]: continue if dominates(data[i], data[j]): index[j] = False elif dominates(data[j], data[i]): index[i] = False break return index ``` ### non_dominated_merge ``` non_dominated_merge( set1: ndarray, set2: ndarray ) -> tuple[np.ndarray, np.ndarray] ``` Merge two sets of non-dominated solutions. This is a slightly more efficient way to merge two sets of solutions such that the resulting set only contains non-dominated solutions from the two sets. This function assumes that the two sets already only contain non-dominated solutions. I.e., each solution in each set is non-dominated with respect to all other solutions in the same set. However, the solutions in the two sets may not be non-dominated with respect to each other. Parameters: | Name | Type | Description | Default | | ------ | --------- | -------------------------------------------------------------- | ---------- | | `set1` | `ndarray` | 2-D array of solutions, with each row being a single solution. | *required* | | `set2` | `ndarray` | 2-D array of solutions, with each row being a single solution. | *required* | Returns: | Type | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[ndarray, ndarray]` | tuple\[np.ndarray, np.ndarray\]: A tuple of two mask arrays. The first mask array is for set1 and the second mask array is for set2. The value of an element in the mask array is True if the corresponding solution is non-dominated in the merged set. False otherwise. | Source code in `desdeo/tools/non_dominated_sorting.py` ``` @njit() def non_dominated_merge(set1: np.ndarray, set2: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Merge two sets of non-dominated solutions. This is a slightly more efficient way to merge two sets of solutions such that the resulting set only contains non-dominated solutions from the two sets. This function assumes that the two sets already only contain non-dominated solutions. I.e., each solution in each set is non-dominated with respect to all other solutions in the same set. However, the solutions in the two sets may not be non-dominated with respect to each other. Args: set1 (np.ndarray): 2-D array of solutions, with each row being a single solution. set2 (np.ndarray): 2-D array of solutions, with each row being a single solution. Returns: tuple[np.ndarray, np.ndarray]: A tuple of two mask arrays. The first mask array is for set1 and the second mask array is for set2. The value of an element in the mask array is True if the corresponding solution is non-dominated in the merged set. False otherwise. """ # Masks to keep track of which solutions are non-dominated. Default is all True. set1_mask = np.ones(len(set1), dtype=np.bool_) set2_mask = np.ones(len(set2), dtype=np.bool_) for i in range(len(set1)): for j in range(len(set2)): if dominates(set1[i], set2[j]): set2_mask[j] = False elif dominates(set2[j], set1[i]): set1_mask[i] = False return set1_mask, set2_mask ``` ## Iterative Pareto representer Implements the Iterative Pareto Representer algorithm. ### \_DSS_with_pruning ``` _DSS_with_pruning( available: ndarray, taken: ndarray ) -> int ``` One-liner implementation of the DSS algorithm using scipy. Source code in `desdeo/tools/iterative_pareto_representer.py` ``` def _DSS_with_pruning( # noqa: N802 available: np.ndarray, taken: np.ndarray, ) -> int: """One-liner implementation of the DSS algorithm using scipy.""" assert len(available) > 0, "No reference points available." # noqa: S101 assert np.allclose( # noqa: S101 available.sum(axis=1), available.shape[1] ), "Reference points must lie on plane perpendicular to ideal-nadir line." assert np.allclose( # noqa: S101 taken.sum(axis=1), taken.shape[1] ), "Reference points must lie on plane perpendicular to ideal-nadir line." if taken is None or len(taken) == 0: return np.random.choice(available) # noqa: NPY002 distances = cdist(available, taken, metric="chebyshev").min(axis=1) return available[np.argmax(distances)] ``` ### \_find_bad_RPs ``` _find_bad_RPs( reference_points_array: ndarray, eval_results: list[_EvaluatedPoint], thickness: float = 0.02, ) -> np.ndarray ``` Find the reference points that will lead to repeated evaluations according to the ASF pruning rule. Source code in `desdeo/tools/iterative_pareto_representer.py` ``` def _find_bad_RPs( # noqa: N802 reference_points_array: np.ndarray, eval_results: list[_EvaluatedPoint], thickness: float = 0.02 ) -> np.ndarray: """Find the reference points that will lead to repeated evaluations according to the ASF pruning rule.""" mask = np.zeros(reference_points_array.shape[0], dtype=bool) def dict_to_numpy(x): return np.array(list(x.values())) for eval_result in eval_results: bad_indices, _, _ = find_bad_indicesREF( dict_to_numpy(eval_result.targets), dict_to_numpy(eval_result.reference_point), reference_points_array, thickness, ) bad_indices = np.where(bad_indices)[0] mask[bad_indices] = True return mask ``` ### \_project ``` _project(solutions) ``` Project the solution to the reference plane defined by the reference_point and the normal vector. Source code in `desdeo/tools/iterative_pareto_representer.py` ``` def _project(solutions): """Project the solution to the reference plane defined by the reference_point and the normal vector.""" reference_point = np.ones(solutions.shape[1]) normal = reference_point / np.linalg.norm(reference_point) perp_dist = np.atleast_2d(np.inner(solutions - reference_point, normal)).T return solutions - perp_dist * normal ``` ### choose_reference_point ``` choose_reference_point( refp_array: ndarray, evaluated_points: list[_EvaluatedPoint] | None = None, ) ``` Choose the next reference point to evaluate using the Iterative Pareto Representer algorithm. Parameters: | Name | Type | Description | Default | | ------------------ | ----------------------- | -------------------------------------------------------------------------------------------------- | ---------- | | `refp_array` | `ndarray` | The reference points to choose from. | *required* | | `evaluated_points` | `list[_EvaluatedPoint]` | Already evaluated reference points and their targets. If None, a random reference point is chosen. | `None` | Source code in `desdeo/tools/iterative_pareto_representer.py` ``` def choose_reference_point( refp_array: np.ndarray, evaluated_points: list[_EvaluatedPoint] | None = None, ): """Choose the next reference point to evaluate using the Iterative Pareto Representer algorithm. Args: refp_array (np.ndarray): The reference points to choose from. evaluated_points (list[_EvaluatedPoint]): Already evaluated reference points and their targets. If None, a random reference point is chosen. """ if evaluated_points is None or len(evaluated_points) == 0: return refp_array[np.random.choice(refp_array.shape[0])], None # noqa: NPY002 bad_points_mask = _find_bad_RPs(refp_array, evaluated_points) available_points_mask = ~bad_points_mask solution_projections = _project(np.array([list(eval_result.targets.values()) for eval_result in evaluated_points])) return _DSS_with_pruning( available=refp_array[available_points_mask], taken=np.vstack((solution_projections, refp_array[bad_points_mask])), ), bad_points_mask ``` ## Intersection Utility methods to check if reference vectors intersect a bounding box. ### find_bad_indicesREF ``` find_bad_indicesREF( solution, ref_point, reference_points, thickness ) ``` Return reference points flagged as bad via line-box intersection, with the box limits. Source code in `desdeo/tools/intersection.py` ``` def find_bad_indicesREF(solution, ref_point, reference_points, thickness): # noqa: N802 """Return reference points flagged as bad via line-box intersection, with the box limits.""" box_max, box_min = find_bad_limits(solution, ref_point) bad_points = line_box_intersection(box_min, box_max, reference_points, thickness) return bad_points, box_min, box_max ``` ### find_bad_limits ``` find_bad_limits(solution, ref_point, threshold=0.05) ``` Return the (max, min) box corners used to flag bad reference points around a solution. Source code in `desdeo/tools/intersection.py` ``` def find_bad_limits(solution, ref_point, threshold=0.05): """Return the (max, min) box corners used to flag bad reference points around a solution.""" # Find projections of solution on the ref direction k = solution - ref_point box_max = ref_point + k.max() box_min = solution return box_max, box_min - threshold / 2 ``` ### line_box_intersection ``` line_box_intersection( box_min: ndarray, box_max: ndarray, reference_points: ndarray, thickness, ) -> np.ndarray ``` Find the reference directions that intersect the box defined by box_min and box_max. Parameters: | Name | Type | Description | Default | | ------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `box_min` | `ndarray` | The infimum of the box. | *required* | | `box_max` | `ndarray` | The supremum of the box. | *required* | | `reference_points` | `ndarray` | The reference directions. | *required* | | `thickness` | `float` | The threshold for thickness. Defines the thickness of the box. The thickness is added to the box_min and subtracted from the box_max to define the box. The reference directions that intersect the box are marked as bad. The thickness is a hyperparameter that needs to be tuned. The default value is 0.05. Try out some values close to 0.05. Lower values will result in lesser number of reference points being marked as bad. Note that a value of zero does not imply that only reference directions that directly intersect the box are marked as bad. Floating point shenanigans (np.isclose) happen. | *required* | Returns: | Type | Description | | --------- | ----------------------------------------------------------------------------------------------------------------------- | | `ndarray` | np.ndarray: A boolean array of length num_points, where True indicates that the reference direction intersects the box. | Source code in `desdeo/tools/intersection.py` ``` def line_box_intersection( box_min: np.ndarray, box_max: np.ndarray, reference_points: np.ndarray, thickness ) -> np.ndarray: """Find the reference directions that intersect the box defined by box_min and box_max. Args: box_min (np.ndarray): The infimum of the box. box_max (np.ndarray): The supremum of the box. reference_points (np.ndarray): The reference directions. thickness (float): The threshold for thickness. Defines the thickness of the box. The thickness is added to the box_min and subtracted from the box_max to define the box. The reference directions that intersect the box are marked as bad. The thickness is a hyperparameter that needs to be tuned. The default value is 0.05. Try out some values close to 0.05. Lower values will result in lesser number of reference points being marked as bad. Note that a value of zero does not imply that only reference directions that directly intersect the box are marked as bad. Floating point shenanigans (np.isclose) happen. Returns: np.ndarray: A boolean array of length num_points, where True indicates that the reference direction intersects the box. """ # Find the reference directions that intersect the box # Vector through the reference point = reference point + k * (nadir - ideal) k_bmin = box_min - reference_points k_bmax = box_max - reference_points # Find the reference directions that intersect the box k_min = np.min((k_bmax, k_bmin), axis=0).max(axis=1) - thickness / 2 k_max = np.max((k_bmax, k_bmin), axis=0).min(axis=1) + thickness / 2 return np.logical_or((k_max >= k_min), np.isclose(k_max, k_min)) ``` ## Interaction schema The schema to represent the interactions of the user. ### Interaction Bases: `BaseModel` The tree-like structure to represent the interactions of the user. Source code in `desdeo/tools/interaction_schema.py` ``` class Interaction(BaseModel): """The tree-like structure to represent the interactions of the user.""" method_name: str = Field(description="The name of the method used for this iteration.") preference_information: dict = Field(description="The preference information given by the user for this iteration.") result: dict = Field( description="The result of the iteration." ) # In the database, this should be a foreign key to the result table next_interaction: list["Interaction"] = Field( description="The next interaction in the tree. This is a list of 'interactions' as " "the user can choose to go back to a previous iteration and change " "the preference information. If the user chooses to go back, just " "append the new interactions to the list in the order they were made." ) # In the database, this should be a foreign key to the interactions table ``` ## Visualizations Provides some visualization functions. ### scatter_plot_comparison ``` scatter_plot_comparison( *results: Any, x_key: str = "f_1", y_key: str = "f_2", z_key: str | None = None, reference_point: dict[str, float] | None = None, names: list[str] | None = None, ) -> go.Figure ``` Plots multiple sets of data in a scatter plot (2D or 3D depending on the data). Parameters: | Name | Type | Description | Default | | ----------------- | ------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | | `*results` | `Any` | Variable number of result objects, each containing outputs with keys for x, y, and optionally z. | `()` | | `x_key` | `str` | Key for the x-axis data in the outputs. | `'f_1'` | | `y_key` | `str` | Key for the y-axis data in the outputs. | `'f_2'` | | `z_key` | \`str | None\` | Key for the z-axis data in the outputs (optional, for 3D plots). | | `reference_point` | \`dict[str, float] | None\` | A dictionary with keys matching x_key, y_key, and optionally z_key, representing the reference point to plot. | | `names` | \`list[str] | None\` | List of names for each data set to display in the legend. | Returns: | Type | Description | | -------- | ------------------------------------------------------- | | `Figure` | go.Figure: A Plotly Figure containing the scatter plot. | Source code in `desdeo/tools/visualizations.py` ``` def scatter_plot_comparison( *results: Any, x_key: str = "f_1", y_key: str = "f_2", z_key: str | None = None, reference_point: dict[str, float] | None = None, names: list[str] | None = None, ) -> go.Figure: """Plots multiple sets of data in a scatter plot (2D or 3D depending on the data). Arguments: *results: Variable number of result objects, each containing outputs with keys for x, y, and optionally z. x_key: Key for the x-axis data in the outputs. y_key: Key for the y-axis data in the outputs. z_key: Key for the z-axis data in the outputs (optional, for 3D plots). reference_point: A dictionary with keys matching x_key, y_key, and optionally z_key, representing the reference point to plot. names: List of names for each data set to display in the legend. Returns: go.Figure: A Plotly Figure containing the scatter plot. """ traces = [] is_3d = z_key is not None and all(z_key in result.outputs for result in results) if names is None: names = [f"Dataset {i + 1}" for i in range(len(results))] for i, (result, name) in enumerate(zip(results, names, strict=False)): color = f"hsl({i * 360 / len(results)}, 100%, 50%)" # Generate distinct colors if is_3d: trace = go.Scatter3d( x=result.outputs[x_key], y=result.outputs[y_key], z=result.outputs[z_key], mode="markers", marker={"size": 4, "color": color, "symbol": "circle"}, name=name, ) else: trace = go.Scatter( x=result.outputs[x_key], y=result.outputs[y_key], mode="markers", marker={"size": 8, "color": color, "symbol": "circle"}, name=name, ) traces.append(trace) if reference_point: if is_3d and z_key: ref_trace = go.Scatter3d( x=[reference_point[x_key]], y=[reference_point[y_key]], z=[reference_point[z_key]], mode="markers", marker={"size": 4, "color": "black", "symbol": "circle"}, name="Reference Point", ) else: ref_trace = go.Scatter( x=[reference_point[x_key]], y=[reference_point[y_key]], mode="markers", marker={"size": 8, "color": "black", "symbol": "circle"}, name="Reference Point", ) traces.append(ref_trace) return go.Figure(data=traces) ``` ## Publisher-Subscriber pattern This module contains the classes for the publisher-subscriber (ish) pattern. The pattern is used in the evolutionary algorithms to send messages between the different components. This allows the components to be decoupled and the messages to be sent between them without the components knowing about each other. The pattern closely resembles the publisher-subscriber pattern, with one key difference. The subscribers can also create messages and send them to the publisher, which then forwards the messages to the other subscribers. The pattern is implemented with two classes: `Subscriber` and `Publisher`. The `Subscriber` class is an abstract class that must be inherited by the classes that want to receive (or send) messages. All evolutionary operators must inherit the `Subscriber` class. Some objects that may be interested in the messages, but otherwise unrelated to the evolutionary operators, may also inherit the `Subscriber` class. Examples of such objects are a logging class, an archive class, or a class that visualizes intermediate results. The `Publisher` class is a class that stores the subscribers and forwards the messages to them. The `Publisher` class is not connected to the evolutionary algorithms and only serves as a message router. As mentioned earlier, the components do not know about each other, and the `Publisher` class is the only class that knows about all the connections in between components. Each subscriber declares the topics it listens for in `interested_topics` and the topics it sends in `provided_topics`, and it registers both with its publisher as soon as it has been constructed. The user can still adjust the wiring afterwards with `subscribe` and `unsubscribe`. The way the pattern works is as follows. Each operator has a `do` method which is called by the evolutionary algorithm when the operator is to be executed. This method has some default arguments, depending upon the class of the operator. E.g., the `do` method of the mutation related classes may have a default arguments as `offsprings` and `parents`, where each is a tuple of decision variables, objectives, and constraints. However, some special mutation operator may require additional inputs. E.g., an adaptive mutation operator may require the current generation number as an input. To provide this additional input, we do not change the signature of the `do` method. Instead, we let the mutation operator subscribe to a topic called, e.g., `current_generation`. The publisher, is then responsible for sending the current generation number to the mutation operator, whenever the generation number changes. The mutation operator can then update its internal state based on the received generation number. To be able to send this information, the `Publisher` class has a method called `notify`. Operators can call this method to send messages to the subscribers. The idea is to do this at the end of the `do` method. That way, whenever any operator is executed, it can send messages to the other operators (which have subscribed to the topics). Note that the operators do not know about the other operators. The subscribers do not know the origin of the messages. This decoupling allows for a more modular design and easier extensibility of the evolutionary algorithms. ### Publisher Class for a publisher that sends messages to subscribers. The publisher is unconnected from the evolutionary algorithms and only serves as a message router. The subscribers can subscribe to different message keys and receive messages when the publisher receives a message with the corresponding key. Source code in `desdeo/tools/patterns.py` ``` class Publisher: """Class for a publisher that sends messages to subscribers. The publisher is unconnected from the evolutionary algorithms and only serves as a message router. The subscribers can subscribe to different message keys and receive messages when the publisher receives a message with the corresponding key. """ def __init__(self) -> None: """Initialize a blank publisher.""" self.subscribers: dict[MessageTopics, list[Subscriber]] = {} self.global_subscribers: list[Subscriber] = [] self.registered_topics: dict[MessageTopics, list[str]] = {} def subscribe(self, subscriber: Subscriber, topic: MessageTopics | Literal["ALL"]) -> None: """Store a subscriber for a given message key. Whenever the publisher receives a message with the given key, it will notify the subscriber. This method can be used to subscribe to multiple topics by calling it multiple times. Moreover, the user can force the subscriber to receive all messages by setting the topic to "ALL". Subscribing the same object to the same topic twice is a no-op. Subscribers register themselves when they are constructed, so an explicit call here is usually redundant, and a duplicate entry would mean `update` being called once per message per duplicate. Args: subscriber (Subscriber): the subscriber to notify. topic (str): the message topic (key in message dictionary) to subscribe to. If "ALL", the subscriber is notified of all messages. """ if topic == "ALL": if not any(x is subscriber for x in self.global_subscribers): self.global_subscribers.append(subscriber) return if topic not in self.subscribers: self.subscribers[topic] = [] if not any(x is subscriber for x in self.subscribers[topic]): self.subscribers[topic].append(subscriber) def auto_subscribe(self, subscriber: Subscriber) -> None: """Store a subscriber for multiple message keys. The subscriber must have the topics attribute. Whenever the publisher receives a message with the given key, it will notify the subscriber. Args: subscriber (Subscriber): the subscriber to notify. """ for topic in subscriber.interested_topics: self.subscribe(subscriber, topic) def unsubscribe(self, subscriber: Subscriber, topic: MessageTopics | Literal["ALL"]) -> None: """Remove a subscriber from a given message key. Args: subscriber (Subscriber): the subscriber to remove. topic (str): the key of the message to unsubscribe from. """ if topic == "ALL": self.global_subscribers.remove(subscriber) return if topic in self.subscribers: self.subscribers[topic].remove(subscriber) def unsubscribe_multiple(self, subscriber: Subscriber, topics: Sequence[MessageTopics | Literal["ALL"]]) -> None: """Remove a subscriber from multiple message keys. Args: subscriber (Subscriber): the subscriber to remove. topics (list[str]): the keys of the messages to unsubscribe from. """ for topic in topics: self.unsubscribe(subscriber, topic) def force_unsubscribe(self, subscriber: Subscriber) -> None: """Remove a subscriber from all message keys. Args: subscriber (Subscriber): the subscriber to remove. """ for topic in self.subscribers: if subscriber in self.subscribers[topic]: self.subscribers[topic].remove(subscriber) def register_topics(self, topics: list[MessageTopics], source: str) -> None: """Register topics provided to the publisher. Registering a source that already provides the topic is a no-op. Subscribers register their own provided topics when they are constructed, so an explicit call here is usually redundant. Args: topics (list[MessageTopics]): the topics to register. source (str): the source of the topics. """ for topic in topics: if topic not in self.registered_topics: self.registered_topics[topic] = [source] elif source not in self.registered_topics[topic]: self.registered_topics[topic].append(source) def check_consistency(self) -> tuple[bool, dict[MessageTopics, list[str]]]: """Check if all subscribed topics have also been registered by a source. Returns: tuple[bool, dict[MessageTopics, list[str]]]: Returns a tuple. The first element is a bool. True if all subscribed topics have been registered by a source. False otherwise. The second element is a dictionary of unregistered topics that have been subscribed to. """ unregistered_topics = {} for topic in self.subscribers: if topic not in self.registered_topics: unregistered_topics[topic] = [x.__class__.__name__ for x in self.subscribers[topic]] if unregistered_topics: return False, unregistered_topics return True, {} def relationship_map(self): """Make a diagram connecting sources to subscribers based on topics.""" relationships = {} for topic in self.subscribers: for subscriber in self.subscribers[topic]: if topic.value not in relationships: relationships[topic.value] = [(subscriber.__class__.__name__, self.registered_topics[topic])] else: relationships[topic.value].append((subscriber.__class__.__name__, self.registered_topics[topic])) return relationships def notify(self, messages: Sequence[Message] | None) -> None: """Notify subscribers of the received message/messages. Args: messages (Sequence[BaseMessage]): the messages to send to the subscribers. Each message is a pydantic model with a topic, value, and a source. """ if messages is None: return for message in messages: # Notify global subscribers for subscriber in self.global_subscribers: subscriber.update(message) # Notify subscribers of the given key if message.topic in self.subscribers: for subscriber in self.subscribers[message.topic]: subscriber.update(message) ``` #### __init__ ``` __init__() -> None ``` Initialize a blank publisher. Source code in `desdeo/tools/patterns.py` ``` def __init__(self) -> None: """Initialize a blank publisher.""" self.subscribers: dict[MessageTopics, list[Subscriber]] = {} self.global_subscribers: list[Subscriber] = [] self.registered_topics: dict[MessageTopics, list[str]] = {} ``` #### auto_subscribe ``` auto_subscribe(subscriber: Subscriber) -> None ``` Store a subscriber for multiple message keys. The subscriber must have the topics attribute. Whenever the publisher receives a message with the given key, it will notify the subscriber. Parameters: | Name | Type | Description | Default | | ------------ | ------------ | ------------------------- | ---------- | | `subscriber` | `Subscriber` | the subscriber to notify. | *required* | Source code in `desdeo/tools/patterns.py` ``` def auto_subscribe(self, subscriber: Subscriber) -> None: """Store a subscriber for multiple message keys. The subscriber must have the topics attribute. Whenever the publisher receives a message with the given key, it will notify the subscriber. Args: subscriber (Subscriber): the subscriber to notify. """ for topic in subscriber.interested_topics: self.subscribe(subscriber, topic) ``` #### check_consistency ``` check_consistency() -> tuple[ bool, dict[MessageTopics, list[str]] ] ``` Check if all subscribed topics have also been registered by a source. Returns: | Type | Description | | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tuple[bool, dict[MessageTopics, list[str]]]` | tuple\[bool, dict\[MessageTopics, list[str]\]\]: Returns a tuple. The first element is a bool. True if all subscribed topics have been registered by a source. False otherwise. The second element is a dictionary of unregistered topics that have been subscribed to. | Source code in `desdeo/tools/patterns.py` ``` def check_consistency(self) -> tuple[bool, dict[MessageTopics, list[str]]]: """Check if all subscribed topics have also been registered by a source. Returns: tuple[bool, dict[MessageTopics, list[str]]]: Returns a tuple. The first element is a bool. True if all subscribed topics have been registered by a source. False otherwise. The second element is a dictionary of unregistered topics that have been subscribed to. """ unregistered_topics = {} for topic in self.subscribers: if topic not in self.registered_topics: unregistered_topics[topic] = [x.__class__.__name__ for x in self.subscribers[topic]] if unregistered_topics: return False, unregistered_topics return True, {} ``` #### force_unsubscribe ``` force_unsubscribe(subscriber: Subscriber) -> None ``` Remove a subscriber from all message keys. Parameters: | Name | Type | Description | Default | | ------------ | ------------ | ------------------------- | ---------- | | `subscriber` | `Subscriber` | the subscriber to remove. | *required* | Source code in `desdeo/tools/patterns.py` ``` def force_unsubscribe(self, subscriber: Subscriber) -> None: """Remove a subscriber from all message keys. Args: subscriber (Subscriber): the subscriber to remove. """ for topic in self.subscribers: if subscriber in self.subscribers[topic]: self.subscribers[topic].remove(subscriber) ``` #### notify ``` notify(messages: Sequence[Message] | None) -> None ``` Notify subscribers of the received message/messages. Parameters: | Name | Type | Description | Default | | ---------- | ----------------------- | ------------------------------------------------------------------------------------------------------------ | ---------- | | `messages` | `Sequence[BaseMessage]` | the messages to send to the subscribers. Each message is a pydantic model with a topic, value, and a source. | *required* | Source code in `desdeo/tools/patterns.py` ``` def notify(self, messages: Sequence[Message] | None) -> None: """Notify subscribers of the received message/messages. Args: messages (Sequence[BaseMessage]): the messages to send to the subscribers. Each message is a pydantic model with a topic, value, and a source. """ if messages is None: return for message in messages: # Notify global subscribers for subscriber in self.global_subscribers: subscriber.update(message) # Notify subscribers of the given key if message.topic in self.subscribers: for subscriber in self.subscribers[message.topic]: subscriber.update(message) ``` #### register_topics ``` register_topics( topics: list[MessageTopics], source: str ) -> None ``` Register topics provided to the publisher. Registering a source that already provides the topic is a no-op. Subscribers register their own provided topics when they are constructed, so an explicit call here is usually redundant. Parameters: | Name | Type | Description | Default | | -------- | --------------------- | ------------------------- | ---------- | | `topics` | `list[MessageTopics]` | the topics to register. | *required* | | `source` | `str` | the source of the topics. | *required* | Source code in `desdeo/tools/patterns.py` ``` def register_topics(self, topics: list[MessageTopics], source: str) -> None: """Register topics provided to the publisher. Registering a source that already provides the topic is a no-op. Subscribers register their own provided topics when they are constructed, so an explicit call here is usually redundant. Args: topics (list[MessageTopics]): the topics to register. source (str): the source of the topics. """ for topic in topics: if topic not in self.registered_topics: self.registered_topics[topic] = [source] elif source not in self.registered_topics[topic]: self.registered_topics[topic].append(source) ``` #### relationship_map ``` relationship_map() ``` Make a diagram connecting sources to subscribers based on topics. Source code in `desdeo/tools/patterns.py` ``` def relationship_map(self): """Make a diagram connecting sources to subscribers based on topics.""" relationships = {} for topic in self.subscribers: for subscriber in self.subscribers[topic]: if topic.value not in relationships: relationships[topic.value] = [(subscriber.__class__.__name__, self.registered_topics[topic])] else: relationships[topic.value].append((subscriber.__class__.__name__, self.registered_topics[topic])) return relationships ``` #### subscribe ``` subscribe( subscriber: Subscriber, topic: MessageTopics | Literal["ALL"], ) -> None ``` Store a subscriber for a given message key. Whenever the publisher receives a message with the given key, it will notify the subscriber. This method can be used to subscribe to multiple topics by calling it multiple times. Moreover, the user can force the subscriber to receive all messages by setting the topic to "ALL". Subscribing the same object to the same topic twice is a no-op. Subscribers register themselves when they are constructed, so an explicit call here is usually redundant, and a duplicate entry would mean `update` being called once per message per duplicate. Parameters: | Name | Type | Description | Default | | ------------ | ------------ | -------------------------------------------------------------------------------------------------------------------- | ---------- | | `subscriber` | `Subscriber` | the subscriber to notify. | *required* | | `topic` | `str` | the message topic (key in message dictionary) to subscribe to. If "ALL", the subscriber is notified of all messages. | *required* | Source code in `desdeo/tools/patterns.py` ``` def subscribe(self, subscriber: Subscriber, topic: MessageTopics | Literal["ALL"]) -> None: """Store a subscriber for a given message key. Whenever the publisher receives a message with the given key, it will notify the subscriber. This method can be used to subscribe to multiple topics by calling it multiple times. Moreover, the user can force the subscriber to receive all messages by setting the topic to "ALL". Subscribing the same object to the same topic twice is a no-op. Subscribers register themselves when they are constructed, so an explicit call here is usually redundant, and a duplicate entry would mean `update` being called once per message per duplicate. Args: subscriber (Subscriber): the subscriber to notify. topic (str): the message topic (key in message dictionary) to subscribe to. If "ALL", the subscriber is notified of all messages. """ if topic == "ALL": if not any(x is subscriber for x in self.global_subscribers): self.global_subscribers.append(subscriber) return if topic not in self.subscribers: self.subscribers[topic] = [] if not any(x is subscriber for x in self.subscribers[topic]): self.subscribers[topic].append(subscriber) ``` #### unsubscribe ``` unsubscribe( subscriber: Subscriber, topic: MessageTopics | Literal["ALL"], ) -> None ``` Remove a subscriber from a given message key. Parameters: | Name | Type | Description | Default | | ------------ | ------------ | ------------------------------------------- | ---------- | | `subscriber` | `Subscriber` | the subscriber to remove. | *required* | | `topic` | `str` | the key of the message to unsubscribe from. | *required* | Source code in `desdeo/tools/patterns.py` ``` def unsubscribe(self, subscriber: Subscriber, topic: MessageTopics | Literal["ALL"]) -> None: """Remove a subscriber from a given message key. Args: subscriber (Subscriber): the subscriber to remove. topic (str): the key of the message to unsubscribe from. """ if topic == "ALL": self.global_subscribers.remove(subscriber) return if topic in self.subscribers: self.subscribers[topic].remove(subscriber) ``` #### unsubscribe_multiple ``` unsubscribe_multiple( subscriber: Subscriber, topics: Sequence[MessageTopics | Literal["ALL"]], ) -> None ``` Remove a subscriber from multiple message keys. Parameters: | Name | Type | Description | Default | | ------------ | ------------ | --------------------------------------------- | ---------- | | `subscriber` | `Subscriber` | the subscriber to remove. | *required* | | `topics` | `list[str]` | the keys of the messages to unsubscribe from. | *required* | Source code in `desdeo/tools/patterns.py` ``` def unsubscribe_multiple(self, subscriber: Subscriber, topics: Sequence[MessageTopics | Literal["ALL"]]) -> None: """Remove a subscriber from multiple message keys. Args: subscriber (Subscriber): the subscriber to remove. topics (list[str]): the keys of the messages to unsubscribe from. """ for topic in topics: self.unsubscribe(subscriber, topic) ``` ### Subscriber Bases: `ABC` Base class for both subscriber and message sender. These are used in the evolutionary algorithms to send messages between the different components. The pattern closely resembles the publisher-subscriber pattern, with one key difference. The subscribers can also create messages and send them to the publisher, which then forwards the messages to the other subscribers. Source code in `desdeo/tools/patterns.py` ``` class Subscriber(ABC, metaclass=_SubscriberMeta): """Base class for both subscriber and message sender. These are used in the evolutionary algorithms to send messages between the different components. The pattern closely resembles the publisher-subscriber pattern, with one key difference. The subscribers can also create messages and send them to the publisher, which then forwards the messages to the other subscribers. """ @property @abstractmethod def interested_topics(self) -> Sequence[MessageTopics]: """Return the topics the subscriber is interested in.""" @property @abstractmethod def provided_topics(self) -> dict[int, Sequence[MessageTopics]]: """Return the topics the subscriber provides to the publisher, grouped by verbosity level.""" def __init__( self, publisher: "Publisher", verbosity: int, ) -> None: """Initialize a subscriber. Args: publisher (Callable): the publisher to send messages to. verbosity (int, optional): the verbosity level of the messages. A value of 0 means no messages at all. """ if not isinstance(verbosity, int): raise TypeError("Verbosity must be an integer.") if verbosity < 0: raise ValueError("Verbosity must be a non-negative integer.") self.publisher = publisher self.verbosity: int = verbosity def __post_init__(self): """Register to the publisher _after_ the subscriber has been initialized. Called by `_SubscriberMeta` when the `__init__` chain of the concrete class has returned, so subclasses need not (and should not) call it themselves. """ self.publisher.auto_subscribe(self) self.publisher.register_topics(self.provided_topics[self.verbosity], self.__class__.__name__) def notify(self) -> None: """Notify the publisher of changes in the subject. The contents of the message (a dictionary) are defined in the `state` method. The `state` method can return different messages depending on the verbosity level. """ if self.verbosity not in AllowedMessagesAtVerbosity: raise ValueError(f"Verbosity level {self.verbosity} is not allowed.") if self.verbosity == 0: return state = self.state() if all(isinstance(x, AllowedMessagesAtVerbosity[self.verbosity]) for x in state): self.publisher.notify(messages=state) @abstractmethod def update(self, message: Message) -> None: """Update self as a result of messages from the publisher. Args: message (Message): the message from the publisher. Note that each message is a pydantic model with a topic, value, and a source. """ @abstractmethod def state(self) -> Sequence[Message]: """Return the state of the subject. This is the list of messages to send to the publisher.""" ``` #### interested_topics ``` interested_topics: Sequence[MessageTopics] ``` Return the topics the subscriber is interested in. #### provided_topics ``` provided_topics: dict[int, Sequence[MessageTopics]] ``` Return the topics the subscriber provides to the publisher, grouped by verbosity level. #### __init__ ``` __init__(publisher: Publisher, verbosity: int) -> None ``` Initialize a subscriber. Parameters: | Name | Type | Description | Default | | ----------- | ---------- | --------------------------------------------------------------------------- | ---------- | | `publisher` | `Callable` | the publisher to send messages to. | *required* | | `verbosity` | `int` | the verbosity level of the messages. A value of 0 means no messages at all. | *required* | Source code in `desdeo/tools/patterns.py` ``` def __init__( self, publisher: "Publisher", verbosity: int, ) -> None: """Initialize a subscriber. Args: publisher (Callable): the publisher to send messages to. verbosity (int, optional): the verbosity level of the messages. A value of 0 means no messages at all. """ if not isinstance(verbosity, int): raise TypeError("Verbosity must be an integer.") if verbosity < 0: raise ValueError("Verbosity must be a non-negative integer.") self.publisher = publisher self.verbosity: int = verbosity ``` #### __post_init__ ``` __post_init__() ``` Register to the publisher *after* the subscriber has been initialized. Called by `_SubscriberMeta` when the `__init__` chain of the concrete class has returned, so subclasses need not (and should not) call it themselves. Source code in `desdeo/tools/patterns.py` ``` def __post_init__(self): """Register to the publisher _after_ the subscriber has been initialized. Called by `_SubscriberMeta` when the `__init__` chain of the concrete class has returned, so subclasses need not (and should not) call it themselves. """ self.publisher.auto_subscribe(self) self.publisher.register_topics(self.provided_topics[self.verbosity], self.__class__.__name__) ``` #### notify ``` notify() -> None ``` Notify the publisher of changes in the subject. The contents of the message (a dictionary) are defined in the `state` method. The `state` method can return different messages depending on the verbosity level. Source code in `desdeo/tools/patterns.py` ``` def notify(self) -> None: """Notify the publisher of changes in the subject. The contents of the message (a dictionary) are defined in the `state` method. The `state` method can return different messages depending on the verbosity level. """ if self.verbosity not in AllowedMessagesAtVerbosity: raise ValueError(f"Verbosity level {self.verbosity} is not allowed.") if self.verbosity == 0: return state = self.state() if all(isinstance(x, AllowedMessagesAtVerbosity[self.verbosity]) for x in state): self.publisher.notify(messages=state) ``` #### state ``` state() -> Sequence[Message] ``` Return the state of the subject. This is the list of messages to send to the publisher. Source code in `desdeo/tools/patterns.py` ``` @abstractmethod def state(self) -> Sequence[Message]: """Return the state of the subject. This is the list of messages to send to the publisher.""" ``` #### update ``` update(message: Message) -> None ``` Update self as a result of messages from the publisher. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------------------------------------------------------------------------------------------- | ---------- | | `message` | `Message` | the message from the publisher. Note that each message is a pydantic model with a topic, value, and a source. | *required* | Source code in `desdeo/tools/patterns.py` ``` @abstractmethod def update(self, message: Message) -> None: """Update self as a result of messages from the publisher. Args: message (Message): the message from the publisher. Note that each message is a pydantic model with a topic, value, and a source. """ ``` ### \_SubscriberMeta Bases: `ABCMeta` Metaclass that calls `__post_init__` once a subscriber is fully initialized. `type.__call__` is the single place where `__new__` and `__init__` are run, so hooking it fires `__post_init__` exactly once per instantiation, however deep the inheritance chain is, and only after the most derived `__init__` has returned. Derives from `ABCMeta` because `Subscriber` is an abstract base class. Note that `__init__` is not run when an instance is unpickled or copied, so `__post_init__` is not either. A subscriber restored in a worker process keeps the subscriptions it was pickled with rather than registering itself a second time. Source code in `desdeo/tools/patterns.py` ``` class _SubscriberMeta(ABCMeta): """Metaclass that calls `__post_init__` once a subscriber is fully initialized. `type.__call__` is the single place where `__new__` and `__init__` are run, so hooking it fires `__post_init__` exactly once per instantiation, however deep the inheritance chain is, and only after the most derived `__init__` has returned. Derives from `ABCMeta` because `Subscriber` is an abstract base class. Note that `__init__` is not run when an instance is unpickled or copied, so `__post_init__` is not either. A subscriber restored in a worker process keeps the subscriptions it was pickled with rather than registering itself a second time. """ def __call__(cls, *args, **kwargs): """Instantiate `cls` as usual, then run the new instance's `__post_init__`.""" instance = super().__call__(*args, **kwargs) instance.__post_init__() return instance ``` #### __call__ ``` __call__(*args, **kwargs) ``` Instantiate `cls` as usual, then run the new instance's `__post_init__`. Source code in `desdeo/tools/patterns.py` ``` def __call__(cls, *args, **kwargs): """Instantiate `cls` as usual, then run the new instance's `__post_init__`.""" instance = super().__call__(*args, **kwargs) instance.__post_init__() return instance ``` ### createblanksubs ``` createblanksubs( interested_topics: Sequence[MessageTopics], ) -> type[Subscriber] ``` Create a blank subscriber for testing purposes. Parameters: | Name | Type | Description | Default | | ------------------- | --------------------- | ------------------------------------------- | ---------- | | `interested_topics` | `list[MessageTopics]` | the topics the subscriber is interested in. | *required* | Returns: | Type | Description | | ------------------ | ----------------------------------------------- | | `type[Subscriber]` | type\[Subscriber\]: the blank subscriber class. | Source code in `desdeo/tools/patterns.py` ``` def createblanksubs(interested_topics: Sequence[MessageTopics]) -> type["Subscriber"]: """Create a blank subscriber for testing purposes. Args: interested_topics (list[MessageTopics]): the topics the subscriber is interested in. Returns: type[Subscriber]: the blank subscriber class. """ class BlankSubscriber(Subscriber): """A simple subscriber for testing purposes.""" @property def interested_topics(self) -> Sequence[MessageTopics]: """Return the topics the subscriber is interested in.""" return interested_topics @property def provided_topics(self) -> dict[int, Sequence[MessageTopics]]: """Return the topics the subscriber provides to the publisher, grouped by verbosity level.""" return {0: []} def __init__(self, publisher: "Publisher", verbosity: int = 0) -> None: """Initialize a subscriber.""" super().__init__(publisher, verbosity) self.messages_to_send: list[Message] = [] self.messages_received: list[Message] = [] def update(self, message: Message) -> None: """Update the internal state of the subscriber.""" self.messages_received.append(message) def state(self) -> list[Message]: """Return the internal state of the subscriber.""" return self.messages_to_send return BlankSubscriber ``` ## Message Topics Defines the messaging protocol used by the various EMO operators. ### Array2DMessage Bases: `BaseMessage` A message containing a 2D array value, such as a population or a set of objectives. Source code in `desdeo/tools/message.py` ``` class Array2DMessage(BaseMessage): """A message containing a 2D array value, such as a population or a set of objectives.""" value: list[list[float]] = Field(..., description="The array value of the message.") """ The array value of the message. """ ``` #### value ``` value: list[list[float]] = Field( ..., description="The array value of the message." ) ``` The array value of the message. ### BaseMessage Bases: `BaseModel` A message containing an integer value. Source code in `desdeo/tools/message.py` ``` class BaseMessage(BaseModel): """A message containing an integer value.""" topic: MessageTopics = Field(..., description="The topic of the message.") """ The topic of the message. """ source: str = Field(..., description="The source of the message.") """ The source of the message. """ ``` #### source ``` source: str = Field( ..., description="The source of the message." ) ``` The source of the message. #### topic ``` topic: MessageTopics = Field( ..., description="The topic of the message." ) ``` The topic of the message. ### BoolMessage Bases: `BaseMessage` A message containing a boolean value. Source code in `desdeo/tools/message.py` ``` class BoolMessage(BaseMessage): """A message containing a boolean value.""" value: bool = Field(..., description="The boolean value of the message.") """ The boolean value of the message. """ ``` #### value ``` value: bool = Field( ..., description="The boolean value of the message." ) ``` The boolean value of the message. ### CrossoverMessageTopics Bases: `Enum` Topics for messages related to crossover operators. Source code in `desdeo/tools/message.py` ``` class CrossoverMessageTopics(Enum): """Topics for messages related to crossover operators.""" TEST = "TEST" """ A message topic used only for testing the crossover operators. """ XOVER_PROBABILITY = "XOVER_PROBABILITY" """ The current crossover probability. """ XOVER_DISTRIBUTION = "XOVER_DISTRIBUTION" """ The current crossover distribution index. Primary used in the SBX crossover. """ PARENTS = "PARENTS" """ The parents selected for crossover. """ OFFSPRINGS = "OFFSPRINGS" """ The offsprings generated from the crossover. """ ALPHA = "ALPHA" """ Alpha parameter used in crossover. """ LAMBDA = "LAMBDA" """ Lambda parameter used in crossover. Primarily used in the bounded exponential xover. """ SCALING_FACTOR = "SCALING_FACTOR" """ The scale applied to a difference vector. Primarily used in differential evolution. """ SIGMA_ZETA = "SIGMA_ZETA" """ Standard deviation along the parent-to-centroid direction. Used in parent-centric crossover. """ SIGMA_ETA = "SIGMA_ETA" """ Standard deviation orthogonal to the parent-to-centroid direction. Used in parent-centric crossover. """ ``` #### ALPHA ``` ALPHA = 'ALPHA' ``` Alpha parameter used in crossover. #### LAMBDA ``` LAMBDA = 'LAMBDA' ``` Lambda parameter used in crossover. Primarily used in the bounded exponential xover. #### OFFSPRINGS ``` OFFSPRINGS = 'OFFSPRINGS' ``` The offsprings generated from the crossover. #### PARENTS ``` PARENTS = 'PARENTS' ``` The parents selected for crossover. #### SCALING_FACTOR ``` SCALING_FACTOR = 'SCALING_FACTOR' ``` The scale applied to a difference vector. Primarily used in differential evolution. #### SIGMA_ETA ``` SIGMA_ETA = 'SIGMA_ETA' ``` Standard deviation orthogonal to the parent-to-centroid direction. Used in parent-centric crossover. #### SIGMA_ZETA ``` SIGMA_ZETA = 'SIGMA_ZETA' ``` Standard deviation along the parent-to-centroid direction. Used in parent-centric crossover. #### TEST ``` TEST = 'TEST' ``` A message topic used only for testing the crossover operators. #### XOVER_DISTRIBUTION ``` XOVER_DISTRIBUTION = 'XOVER_DISTRIBUTION' ``` The current crossover distribution index. Primary used in the SBX crossover. #### XOVER_PROBABILITY ``` XOVER_PROBABILITY = 'XOVER_PROBABILITY' ``` The current crossover probability. ### DictMessage Bases: `BaseMessage` A message containing a dictionary value. Source code in `desdeo/tools/message.py` ``` class DictMessage(BaseMessage): """A message containing a dictionary value.""" value: dict[str, Any] = Field(..., description="The dictionary value of the message.") """ The dictionary value of the message. """ ``` #### value ``` value: dict[str, Any] = Field( ..., description="The dictionary value of the message." ) ``` The dictionary value of the message. ### EvaluatorMessageTopics Bases: `Enum` Topics for messages related to evaluator operators. Source code in `desdeo/tools/message.py` ``` class EvaluatorMessageTopics(Enum): """Topics for messages related to evaluator operators.""" TEST = "TEST" """ A message topic used only for testing the evaluator operators. """ POPULATION = "POPULATION" """ The population to evaluate. """ OUTPUTS = "OUTPUTS" """ The outputs of the population. Contains objectives, targets, constraints. """ OBJECTIVES = "OBJECTIVES" """ The true objective values of the population. """ TARGETS = "TARGETS" """ The targets, i.e., objective values seen by the evolutionary operators.""" CONSTRAINTS = "CONSTRAINTS" """ The constraints of the population. """ VERBOSE_OUTPUTS = "VERBOSE_OUTPUTS" """ Same as POPULATION + OUTPUTS.""" NEW_EVALUATIONS = "NEW_EVALUATIONS" """ The number of new evaluations. """ ``` #### CONSTRAINTS ``` CONSTRAINTS = 'CONSTRAINTS' ``` The constraints of the population. #### NEW_EVALUATIONS ``` NEW_EVALUATIONS = 'NEW_EVALUATIONS' ``` The number of new evaluations. #### OBJECTIVES ``` OBJECTIVES = 'OBJECTIVES' ``` The true objective values of the population. #### OUTPUTS ``` OUTPUTS = 'OUTPUTS' ``` The outputs of the population. Contains objectives, targets, constraints. #### POPULATION ``` POPULATION = 'POPULATION' ``` The population to evaluate. #### TARGETS ``` TARGETS = 'TARGETS' ``` The targets, i.e., objective values seen by the evolutionary operators. #### TEST ``` TEST = 'TEST' ``` A message topic used only for testing the evaluator operators. #### VERBOSE_OUTPUTS ``` VERBOSE_OUTPUTS = 'VERBOSE_OUTPUTS' ``` Same as POPULATION + OUTPUTS. ### FloatMessage Bases: `BaseMessage` A message containing a float value. Source code in `desdeo/tools/message.py` ``` class FloatMessage(BaseMessage): """A message containing a float value.""" value: float = Field(..., description="The float value of the message.") """ The float value of the message. """ ``` #### value ``` value: float = Field( ..., description="The float value of the message." ) ``` The float value of the message. ### GeneratorMessageTopics Bases: `Enum` Topics for messages related to population generator operators. Source code in `desdeo/tools/message.py` ``` class GeneratorMessageTopics(Enum): """Topics for messages related to population generator operators.""" TEST = "TEST" """ A message topic used only for testing the evaluator operators. """ POPULATION = "POPULATION" """ The population to evaluate. """ OUTPUTS = "OUTPUTS" """ The outputs of the population generation. Contains objectives, targets, and constraints. """ OBJECTIVES = "OBJECTIVES" """ The true objective values of the population. """ TARGETS = "TARGETS" """ The targets, i.e., objective values seen by the evolutionary operators.""" CONSTRAINTS = "CONSTRAINTS" """ The constraints of the population. """ VERBOSE_OUTPUTS = "VERBOSE_OUTPUTS" """ Same as POPULATION + OUTPUTS. """ NEW_EVALUATIONS = "NEW_EVALUATIONS" """ The number of new evaluations. """ ``` #### CONSTRAINTS ``` CONSTRAINTS = 'CONSTRAINTS' ``` The constraints of the population. #### NEW_EVALUATIONS ``` NEW_EVALUATIONS = 'NEW_EVALUATIONS' ``` The number of new evaluations. #### OBJECTIVES ``` OBJECTIVES = 'OBJECTIVES' ``` The true objective values of the population. #### OUTPUTS ``` OUTPUTS = 'OUTPUTS' ``` The outputs of the population generation. Contains objectives, targets, and constraints. #### POPULATION ``` POPULATION = 'POPULATION' ``` The population to evaluate. #### TARGETS ``` TARGETS = 'TARGETS' ``` The targets, i.e., objective values seen by the evolutionary operators. #### TEST ``` TEST = 'TEST' ``` A message topic used only for testing the evaluator operators. #### VERBOSE_OUTPUTS ``` VERBOSE_OUTPUTS = 'VERBOSE_OUTPUTS' ``` Same as POPULATION + OUTPUTS. ### GenericMessage Bases: `BaseMessage` A message containing a generic value. Source code in `desdeo/tools/message.py` ``` class GenericMessage(BaseMessage): """A message containing a generic value.""" value: Any = Field(..., description="The generic value of the message.") """ The generic value of the message. """ ``` #### value ``` value: Any = Field( ..., description="The generic value of the message." ) ``` The generic value of the message. ### IntMessage Bases: `BaseMessage` A message containing an integer value. Source code in `desdeo/tools/message.py` ``` class IntMessage(BaseMessage): """A message containing an integer value.""" value: int = Field(..., description="The integer value of the message.") """ The integer value of the message. """ ``` #### value ``` value: int = Field( ..., description="The integer value of the message." ) ``` The integer value of the message. ### MutationMessageTopics Bases: `Enum` Topics for messages related to mutation operators. Source code in `desdeo/tools/message.py` ``` class MutationMessageTopics(Enum): """Topics for messages related to mutation operators.""" TEST = "TEST" """ A message topic used only for testing the mutation operators. """ MUTATION_PROBABILITY = "MUTATION_PROBABILITY" """ The current mutation probability. """ MUTATION_DISTRIBUTION = "MUTATION_DISTRIBUTION" """ The current mutation distribution index. Primary used in the polynomial mutation. """ OFFSPRING_ORIGINAL = "OFFSPRING_ORIGINAL" """ The original offsprings before mutation. """ OFFSPRINGS = "OFFSPRINGS" """ The offsprings after mutation. """ PARENTS = "PARENTS" """ The parents of the offsprings. """ ``` #### MUTATION_DISTRIBUTION ``` MUTATION_DISTRIBUTION = 'MUTATION_DISTRIBUTION' ``` The current mutation distribution index. Primary used in the polynomial mutation. #### MUTATION_PROBABILITY ``` MUTATION_PROBABILITY = 'MUTATION_PROBABILITY' ``` The current mutation probability. #### OFFSPRINGS ``` OFFSPRINGS = 'OFFSPRINGS' ``` The offsprings after mutation. #### OFFSPRING_ORIGINAL ``` OFFSPRING_ORIGINAL = 'OFFSPRING_ORIGINAL' ``` The original offsprings before mutation. #### PARENTS ``` PARENTS = 'PARENTS' ``` The parents of the offsprings. #### TEST ``` TEST = 'TEST' ``` A message topic used only for testing the mutation operators. ### NumpyArrayMessage Bases: `BaseMessage` A message containing a numpy array value. Source code in `desdeo/tools/message.py` ``` class NumpyArrayMessage(BaseMessage): """A message containing a numpy array value.""" value: np.ndarray = Field(..., description="The numpy array value of the message.") """ The numpy array value of the message. """ model_config = ConfigDict(arbitrary_types_allowed=True) @field_serializer("value") def _serialize_value(self, value: np.ndarray) -> list[list[float]]: return value.tolist() ``` #### value ``` value: ndarray = Field( ..., description="The numpy array value of the message." ) ``` The numpy array value of the message. ### PolarsDataFrameMessage Bases: `BaseMessage` A message containing a 2D array value, such as a population or a set of objectives. Source code in `desdeo/tools/message.py` ``` class PolarsDataFrameMessage(BaseMessage): """A message containing a 2D array value, such as a population or a set of objectives.""" value: DataFrame = Field(..., description="The array value of the message.") """ The array value of the message. """ model_config = ConfigDict(arbitrary_types_allowed=True) @field_serializer("value") def _serialize_value(self, value: DataFrame) -> dict[str, list[int | float]]: return value.to_dict(as_series=False) ``` #### value ``` value: DataFrame = Field( ..., description="The array value of the message." ) ``` The array value of the message. ### ReferenceVectorMessageTopics Bases: `Enum` Topics for messages related to the reference vectors. Source code in `desdeo/tools/message.py` ``` class ReferenceVectorMessageTopics(Enum): """Topics for messages related to the reference vectors.""" TEST = "TEST" ``` ### SelectorMessageTopics Bases: `Enum` Topics for messages related to selector operators. Source code in `desdeo/tools/message.py` ``` class SelectorMessageTopics(Enum): """Topics for messages related to selector operators.""" TEST = "TEST" """ A message topic used only for testing the selector operators. """ STATE = "STATE" """ The state of the parameters of the selector. """ INDIVIDUALS = "INDIVIDUALS" """ The individuals to select from. """ OUTPUTS = "OUTPUTS" """ The outputs of the individuals. """ CONSTRAINTS = "CONSTRAINTS" """ The constraints of the individuals. """ SELECTED_INDIVIDUALS = "SELECTED_INDIVIDUALS" """ The individuals selected by the selector. """ SELECTED_OUTPUTS = "SELECTED_OUTPUTS" """ The targets of the selected individuals. """ SELECTED_FITNESS = "SELECTED_FITNESS" """ The fitness of the selected individuals. This is the fitness calculated by the selector, not the objectives.""" SELECTED_VERBOSE_OUTPUTS = "SELECTED_VERBOSE_OUTPUTS" """ Same as SELECTED_OUTPUTS + SELECTED_INDIVIDUALS""" REFERENCE_VECTORS = "REFERENCE_VECTORS" """ The reference vectors used in the selection in decomposition-based EMO algorithms. """ ``` #### CONSTRAINTS ``` CONSTRAINTS = 'CONSTRAINTS' ``` The constraints of the individuals. #### INDIVIDUALS ``` INDIVIDUALS = 'INDIVIDUALS' ``` The individuals to select from. #### OUTPUTS ``` OUTPUTS = 'OUTPUTS' ``` The outputs of the individuals. #### REFERENCE_VECTORS ``` REFERENCE_VECTORS = 'REFERENCE_VECTORS' ``` The reference vectors used in the selection in decomposition-based EMO algorithms. #### SELECTED_FITNESS ``` SELECTED_FITNESS = 'SELECTED_FITNESS' ``` The fitness of the selected individuals. This is the fitness calculated by the selector, not the objectives. #### SELECTED_INDIVIDUALS ``` SELECTED_INDIVIDUALS = 'SELECTED_INDIVIDUALS' ``` The individuals selected by the selector. #### SELECTED_OUTPUTS ``` SELECTED_OUTPUTS = 'SELECTED_OUTPUTS' ``` The targets of the selected individuals. #### SELECTED_VERBOSE_OUTPUTS ``` SELECTED_VERBOSE_OUTPUTS = 'SELECTED_VERBOSE_OUTPUTS' ``` Same as SELECTED_OUTPUTS + SELECTED_INDIVIDUALS #### STATE ``` STATE = 'STATE' ``` The state of the parameters of the selector. #### TEST ``` TEST = 'TEST' ``` A message topic used only for testing the selector operators. ### StringMessage Bases: `BaseMessage` A message containing a string value. Source code in `desdeo/tools/message.py` ``` class StringMessage(BaseMessage): """A message containing a string value.""" value: str = Field(..., description="The string value of the message.") """ The string value of the message. """ ``` #### value ``` value: str = Field( ..., description="The string value of the message." ) ``` The string value of the message. ### TerminatorMessageTopics Bases: `Enum` Topics for messages related to terminator operators. Source code in `desdeo/tools/message.py` ``` class TerminatorMessageTopics(Enum): """Topics for messages related to terminator operators.""" TEST = "TEST" """ A message topic used only for testing the terminator operators. """ STATE = "STATE" """ The state of the parameters of the terminator. """ TERMINATION = "TERMINATION" """ The value of the termination condition. """ GENERATION = "GENERATION" """ The current generation number. """ EVALUATION = "EVALUATION" """ The current number of evaluations. """ MAX_GENERATIONS = "MAX_GENERATIONS" """ The maximum number of generations. """ MAX_EVALUATIONS = "MAX_EVALUATIONS" """ The maximum number of evaluations. """ ``` #### EVALUATION ``` EVALUATION = 'EVALUATION' ``` The current number of evaluations. #### GENERATION ``` GENERATION = 'GENERATION' ``` The current generation number. #### MAX_EVALUATIONS ``` MAX_EVALUATIONS = 'MAX_EVALUATIONS' ``` The maximum number of evaluations. #### MAX_GENERATIONS ``` MAX_GENERATIONS = 'MAX_GENERATIONS' ``` The maximum number of generations. #### STATE ``` STATE = 'STATE' ``` The state of the parameters of the terminator. #### TERMINATION ``` TERMINATION = 'TERMINATION' ``` The value of the termination condition. #### TEST ``` TEST = 'TEST' ``` A message topic used only for testing the terminator operators. ## Description generator An utility function to generate descriptions related to UTOPIA matters. ### generate_descriptions ``` generate_descriptions( mapjson: dict, sid: str, stand: str, holding: str, extension: str, ) -> dict ``` Generate human-readable stand descriptions for UTOPIA forest map features. Source code in `desdeo/tools/desc_gen.py` ``` def generate_descriptions(mapjson: dict, sid: str, stand: str, holding: str, extension: str) -> dict: """Generate human-readable stand descriptions for UTOPIA forest map features.""" descriptions = {} if holding: for feat in mapjson["features"]: if False: # noqa: SIM108 ext = f".{feat['properties'][extension]}" else: ext = "" descriptions[feat["properties"][sid]] = ( f"Ala {feat['properties'][holding].split('-')[-1]} kuvio {feat['properties'][stand]}{ext}: " ) else: for feat in mapjson["features"]: if False: # noqa: SIM108 ext = f".{feat['properties'][extension]}" else: ext = "" descriptions[feat["properties"][sid]] = f"Kuvio {feat['properties'][stand]}{ext}: " return descriptions ``` ## Utilities General utilities related to solvers. ### find_compatible_solvers ``` find_compatible_solvers( problem: Problem, ) -> list[BaseSolver] ``` Find solvers that are compatible with the problem that is being solved. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------- | ---------- | | `problem` | `Problem` | The problem being solved. | *required* | Returns: | Type | Description | | ------------------ | --------------------------------------------------------------------------- | | `list[BaseSolver]` | list\[BaseSolver\]: A list of solvers that are compatible with the problem. | Source code in `desdeo/tools/utils.py` ``` def find_compatible_solvers(problem: Problem) -> list[BaseSolver]: """Find solvers that are compatible with the problem that is being solved. Args: problem (Problem): The problem being solved. Returns: list[BaseSolver]: A list of solvers that are compatible with the problem. """ solvers = [] # check for variable dimensions # This could be also done by just checking if all the variables are Variables instead of TensorVariables # as solvers at the moment do not care about the difference between 1D tensors and higher dimensions. # This is because the solvers that utilize the polars evaluator (the only evaluator that works with # scalars and 1D tensors and not higher dimensions) only support scalar valued variables at the moment. var_dim = variable_dimension_enumerate(problem) # check if problem has only data-based objectives all_data_based = all(objective.objective_type == ObjectiveTypeEnum.data_based for objective in problem.objectives) # check if problem has a discrete definition has_discrete = problem.discrete_representation is not None # check if problem is data-based if all_data_based and has_discrete and var_dim == VariableDimensionEnum.scalar: # problem has only data-based objectives and a discrete definition is available # return ProximalSolver as it is the only solver for data-based problems at the moment return [available_solvers["proximal"]["constructor"]] # check if the problem is differentiable and if it is mixed integer if ( problem.is_twice_differentiable and shutil.which("bonmin") and problem.variable_domain in [ VariableDomainTypeEnum.integer, VariableDomainTypeEnum.mixed, ] ): solvers.append(available_solvers["pyomo_bonmin"]["constructor"]) # bonmin has to be installed # check if the problem is differentiable and continuous if ( problem.is_twice_differentiable and shutil.which("ipopt") and problem.variable_domain == VariableDomainTypeEnum.continuous ): solvers.append(available_solvers["pyomo_ipopt"]["constructor"]) # ipopt has to be installed # check if the problem is convex or log-log convex if check_cvxpy_suitability(problem): solvers.append(available_solvers["cvxpy"]["constructor"]) # check if the problem is linear if problem.is_linear and check_gurobi_license(): solvers.append(available_solvers["gurobipy"]["constructor"]) if problem.is_linear and shutil.which("gurobi"): solvers.append(available_solvers["pyomo_gurobi"]["constructor"]) # gurobi has to be installed if problem.is_linear and shutil.which("cbc"): solvers.append(available_solvers["pyomo_cbc"]["constructor"]) # check if problem's variables are all scalars if var_dim == VariableDimensionEnum.scalar: # nevergrad and scipy solvers work with all(?) problems with only scalar valued variables solvers.append(available_solvers["nevergrad"]["constructor"]) solvers.append(available_solvers["scipy_minimize"]["constructor"]) solvers.append(available_solvers["scipy_de"]["constructor"]) return solvers ``` ### flip_maximized_objective_values ``` flip_maximized_objective_values( problem: Problem, objective_values: dict[str, float] ) -> dict[str, float] ``` Flips the objective values if the objective function is to be maximized. Flips the objective values if the objective function is to be maximized by multiplying the values related to maximized objective functions by -1. Parameters: | Name | Type | Description | Default | | ------------------ | ------------------ | ------------------------------------------------ | ---------- | | `problem` | `Problem` | the problem the objective values are related to. | *required* | | `objective_values` | `dict[str, float]` | the objective values to be flipped. | *required* | Returns: | Type | Description | | ------------------ | ------------------------------------------------- | | `dict[str, float]` | dict\[str, float\]: the flipped objective values. | Source code in `desdeo/tools/utils.py` ``` def flip_maximized_objective_values(problem: Problem, objective_values: dict[str, float]) -> dict[str, float]: """Flips the objective values if the objective function is to be maximized. Flips the objective values if the objective function is to be maximized by multiplying the values related to maximized objective functions by -1. Args: problem (Problem): the problem the objective values are related to. objective_values (dict[str, float]): the objective values to be flipped. Returns: dict[str, float]: the flipped objective values. """ return { obj.symbol: objective_values[obj.symbol] * -1 if obj.maximize else objective_values[obj.symbol] for obj in problem.objectives } ``` ### get_corrected_ideal ``` get_corrected_ideal( problem: Problem, ) -> dict[str, float | None] ``` Compute the corrected ideal point depending if an objective function is to be maximized or not. I.e., the ideal point element for objectives to be maximized will be multiplied by -1. Parameters: | Name | Type | Description | Default | | --------- | --------- | --------------------------------- | ---------- | | `problem` | `Problem` | the problem with the ideal point. | *required* | Raises: | Type | Description | | ------------ | ------------------------------------------------------------------------------------ | | `ValueError` | some of the ideal point components have not been defined for some of the objectives. | Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | None\]\` | Source code in `desdeo/tools/utils.py` ``` def get_corrected_ideal(problem: Problem) -> dict[str, float | None]: """Compute the corrected ideal point depending if an objective function is to be maximized or not. I.e., the ideal point element for objectives to be maximized will be multiplied by -1. Args: problem (Problem): the problem with the ideal point. Raises: ValueError: some of the ideal point components have not been defined for some of the objectives. Returns: list[float]: a list with the corrected ideal point. Will return None for missing elements. """ # check that ideal points are actually defined if any(obj.ideal is None for obj in problem.objectives): msg = "Some of the objectives have not a defined ideal value." raise ValueError(msg) return { objective.symbol: objective.ideal if not objective.maximize else -objective.ideal for objective in problem.objectives } ``` ### get_corrected_ideal_and_nadir ``` get_corrected_ideal_and_nadir( problem: Problem, ) -> tuple[ dict[str, float | None], dict[str, float | None] | None ] ``` Compute the corrected ideal and nadir points depending if an objective function is to be maximized or not. I.e., the ideal and nadir point element for objectives to be maximized will be multiplied by -1. Parameters: | Name | Type | Description | Default | | --------- | --------- | -------------------------------------------- | ---------- | | `problem` | `Problem` | the problem with the ideal and nadir points. | *required* | Raises: | Type | Description | | ------------ | --------------------------------------------------------------------------------------------- | | `ValueError` | some of the ideal or nadir point components have not been defined for some of the objectives. | Returns: | Type | Description | | ------------------------- | ------------------------ | | \`tuple\[dict\[str, float | None\], dict\[str, float | Source code in `desdeo/tools/utils.py` ``` def get_corrected_ideal_and_nadir(problem: Problem) -> tuple[dict[str, float | None], dict[str, float | None] | None]: """Compute the corrected ideal and nadir points depending if an objective function is to be maximized or not. I.e., the ideal and nadir point element for objectives to be maximized will be multiplied by -1. Args: problem (Problem): the problem with the ideal and nadir points. Raises: ValueError: some of the ideal or nadir point components have not been defined for some of the objectives. Returns: tuple[list[float], list[float]]: a list with the corrected ideal point and a list with the corrected nadir point. Will return None for missing elements. """ # check that ideal and nadir points are actually defined if any(obj.ideal is None for obj in problem.objectives) or any(obj.nadir is None for obj in problem.objectives): msg = "Some of the objectives have not a defined ideal or nadir value." raise ValueError(msg) ideal_point = { objective.symbol: objective.ideal if not objective.maximize else -objective.ideal for objective in problem.objectives } nadir_point = { objective.symbol: objective.nadir if not objective.maximize else -objective.nadir for objective in problem.objectives } return ideal_point, nadir_point ``` ### get_corrected_nadir ``` get_corrected_nadir( problem: Problem, ) -> dict[str, float | None] ``` Compute the corrected nadir point depending if an objective function is to be maximized or not. I.e., the nadir point element for objectives to be maximized will be multiplied by -1. Parameters: | Name | Type | Description | Default | | --------- | --------- | ---------------------------------- | ---------- | | `problem` | `Problem` | the problem with the nadir points. | *required* | Raises: | Type | Description | | ------------ | ------------------------------------------------------------------------------------ | | `ValueError` | some of the nadir point components have not been defined for some of the objectives. | Returns: | Type | Description | | ------------------ | ----------- | | \`dict\[str, float | None\]\` | Source code in `desdeo/tools/utils.py` ``` def get_corrected_nadir(problem: Problem) -> dict[str, float | None]: """Compute the corrected nadir point depending if an objective function is to be maximized or not. I.e., the nadir point element for objectives to be maximized will be multiplied by -1. Args: problem (Problem): the problem with the nadir points. Raises: ValueError: some of the nadir point components have not been defined for some of the objectives. Returns: list[float]: a list with the corrected nadir point. Will return None for missing elements. """ # check that nadir points are actually defined if any(obj.nadir is None for obj in problem.objectives): msg = "Some of the objectives have not a defined nadir value." raise ValueError(msg) return { objective.symbol: objective.nadir if not objective.maximize else -objective.nadir for objective in problem.objectives } ``` ### guess_best_solver ``` guess_best_solver(problem: Problem) -> BaseSolver ``` Given a problem, tries to guess the best solver to handle it. Parameters: | Name | Type | Description | Default | | --------- | --------- | ------------------------- | ---------- | | `problem` | `Problem` | the problem being solved. | *required* | Note Needs to be extended as new solvers are implemented. Returns: | Name | Type | Description | | ------------ | ------------ | --------------------------------------------------- | | `BaseSolver` | `BaseSolver` | a solver class that uses BaseSolver as a base class | Source code in `desdeo/tools/utils.py` ``` def guess_best_solver(problem: Problem) -> BaseSolver: """Given a problem, tries to guess the best solver to handle it. Args: problem (Problem): the problem being solved. Note: Needs to be extended as new solvers are implemented. Returns: BaseSolver: a solver class that uses BaseSolver as a base class """ # needs to be extended as new solver are implemented # check if problem has only data-based objectives all_data_based = all(objective.objective_type == ObjectiveTypeEnum.data_based for objective in problem.objectives) # check if problem has a discrete definition has_discrete = problem.discrete_representation is not None # TODO: when figured out what solver is best for problems with tensor variables: it seems that e.g. the # forest problems don't work with pyomo_cbc. So VERY MUCH a quick fix to get something working, as those types of # problems have been ok with gurobipy. # if True in [isinstance(variable, TensorVariable) for variable in problem.variables]: if False: if problem.is_linear and shutil.which("cbc"): return available_solvers["pyomo_cbc"]["constructor"] if problem.is_linear: return available_solvers["gurobipy"]["constructor"] # check if the problem is differentiable and if it is mixed integer if ( problem.is_twice_differentiable and shutil.which("bonmin") and problem.variable_domain in [ VariableDomainTypeEnum.integer, VariableDomainTypeEnum.mixed, ] ): return available_solvers["pyomo_bonmin"]["constructor"] # check if the problem is differentiable and continuous if ( problem.is_twice_differentiable and shutil.which("ipopt") and problem.variable_domain == VariableDomainTypeEnum.continuous ): return available_solvers["pyomo_ipopt"]["constructor"] if all_data_based and has_discrete: # problem has only data-based objectives and a discrete definition is available # guess proximal solver is best return available_solvers["proximal"]["constructor"] # check if the problem is linear if problem.is_linear and check_gurobi_license(): return available_solvers["gurobipy"]["constructor"] # check if the problem is convex or log-log convex if check_cvxpy_suitability(problem): return available_solvers["cvxpy"]["constructor"] # check if the problem is differentiable and if it is mixed integer if ( problem.is_twice_differentiable and shutil.which("bonmin") and problem.variable_domain in [ VariableDomainTypeEnum.integer, VariableDomainTypeEnum.mixed, ] ): return available_solvers["pyomo_bonmin"]["constructor"] # check if the problem is differentiable and continuous if ( problem.is_twice_differentiable and shutil.which("ipopt") and problem.variable_domain == VariableDomainTypeEnum.continuous ): return available_solvers["pyomo_ipopt"]["constructor"] # else, guess nevergrad heuristics to be the best return available_solvers["nevergrad"]["constructor"] ``` ### payoff_table_method ``` payoff_table_method( problem: Problem, solver: BaseSolver = None ) -> tuple[dict[str, float], dict[str, float]] ``` Solves a representation for the ideal and nadir points for a multiobjective optimization problem. Parameters: | Name | Type | Description | Default | | --------- | ------------ | -------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem for which the ideal and nadir are solved. | *required* | | `solver` | `BaseSolver` | The solver to be used in solving the points. Defaults to None. | `None` | Returns: | Type | Description | | ------------------------------------------- | ---------------------------------------------------------------------------------- | | `tuple[dict[str, float], dict[str, float]]` | tuple\[dict[str, float], dict[str, float]\]: The estimated ideal and nadir points. | Source code in `desdeo/tools/utils.py` ``` def payoff_table_method(problem: Problem, solver: BaseSolver = None) -> tuple[dict[str, float], dict[str, float]]: """Solves a representation for the ideal and nadir points for a multiobjective optimization problem. Args: problem (Problem): The problem for which the ideal and nadir are solved. solver (BaseSolver): The solver to be used in solving the points. Defaults to None. Returns: tuple[dict[str, float], dict[str, float]]: The estimated ideal and nadir points. """ solver = solver if solver is not None else guess_best_solver(problem) solver = solver(problem) k = len(problem.objectives) po_table = np.zeros((k, k)) for i in range(k): res = solver.solve(f"{problem.objectives[i].symbol}_min") for j in range(k): po_table[i][j] = res.optimal_objectives[problem.objectives[j].symbol] ideal = np.diag(po_table) nadir = [] for i in range(k): if problem.objectives[i].maximize: nadir.append(np.min(po_table.T[i])) else: nadir.append(np.max(po_table.T[i])) return numpy_array_to_objective_dict(problem, ideal), numpy_array_to_objective_dict(problem, nadir) ``` ### repair ``` repair( lower_bounds: dict[str, float], upper_bounds: dict[str, float], ) -> Callable[[pl.DataFrame], pl.DataFrame] ``` Repairs the offspring by clipping the values to be within the specified bounds. Useful in evolutionary algorithms where offspring may go out of bounds due to crossover or mutation operations. This also fills any NaN values with the mean of the lower and upper bounds for that variable. Certain operators are known to produce NaN values, e.g., the Bounded Exponential Crossover operator. Parameters: | Name | Type | Description | Default | | -------------- | ------------------ | ----------------------------------- | ---------- | | `lower_bounds` | `dict[str, float]` | The lower bounds for each variable. | *required* | | `upper_bounds` | `dict[str, float]` | The upper bounds for each variable. | *required* | Returns: | Type | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `Callable[[DataFrame], DataFrame]` | Callable\[[pl.DataFrame], pl.DataFrame\]: A function that takes a DataFrame and returns a repaired DataFrame. | Source code in `desdeo/tools/utils.py` ``` def repair(lower_bounds: dict[str, float], upper_bounds: dict[str, float]) -> Callable[[pl.DataFrame], pl.DataFrame]: """Repairs the offspring by clipping the values to be within the specified bounds. Useful in evolutionary algorithms where offspring may go out of bounds due to crossover or mutation operations. This also fills any NaN values with the mean of the lower and upper bounds for that variable. Certain operators are known to produce NaN values, e.g., the Bounded Exponential Crossover operator. Args: lower_bounds (dict[str, float]): The lower bounds for each variable. upper_bounds (dict[str, float]): The upper bounds for each variable. Returns: Callable[[pl.DataFrame], pl.DataFrame]: A function that takes a DataFrame and returns a repaired DataFrame. """ def actual_repair(offspring: pl.DataFrame) -> pl.DataFrame: for var in offspring.columns: mean = (upper_bounds[var] + lower_bounds[var]) / 2 offspring = offspring.with_columns( pl.col(var).clip(lower_bound=lower_bounds[var], upper_bound=upper_bounds[var]).fill_nan(mean) ) return offspring # The original code seemed too slow when offsprings were created one at a time? # This is just a quick fix. def fast_actual_repair(offspring: pl.DataFrame) -> pl.DataFrame: # Convert the DataFrame to a NumPy array for faster operations. The values and both bounds # are taken in the same column order. columns = list(upper_bounds.keys()) offspring_np = offspring[columns].to_numpy().astype(float) lower_bounds_np = np.array([lower_bounds[var] for var in columns], dtype=float) upper_bounds_np = np.array([upper_bounds[var] for var in columns], dtype=float) # Clip the values to be within the specified bounds offspring_np = np.clip(offspring_np, lower_bounds_np, upper_bounds_np) # Fill NaN values with the mean of the lower and upper bounds means = (upper_bounds_np + lower_bounds_np) / 2 nan_mask = np.isnan(offspring_np) offspring_np[nan_mask] = np.take(means, np.where(nan_mask)[1]) # `orient="row"` is required: with as many offspring as variables the array is square, and # polars then reads it column by column, which transposed the whole offspring block. repaired = pl.DataFrame(offspring_np, schema=columns, orient="row") return offspring.with_columns(repaired.get_columns()) return fast_actual_repair ``` ## Generics Defines generic classes, functions, and objects utilized in the tools module. ### BaseSolver Bases: `ABC` Defines a schema for a solver base class. Source code in `desdeo/tools/generics.py` ``` class BaseSolver(ABC): """Defines a schema for a solver base class.""" evaluator: object problem: Problem def __init__(self, problem: Problem, options: dict[str, Any] | None = None): """Initializer for the persistent solver. Args: problem (Problem): The problem for the solver. options (dict[str,any]): Dictionary of parameters to set. What these should be depends on the solver used. """ self.problem = problem @abstractmethod def solve(self, target: str) -> SolverResults: """Solves the current problem with the specified target. Args: target (str): a str representing the symbol of the target function. Returns: SolverResults: The results of the solver """ ``` #### __init__ ``` __init__( problem: Problem, options: dict[str, Any] | None = None ) ``` Initializer for the persistent solver. Parameters: | Name | Type | Description | Default | | --------- | ---------------- | --------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem for the solver. | *required* | | `options` | `dict[str, any]` | Dictionary of parameters to set. What these should be depends on the solver used. | `None` | Source code in `desdeo/tools/generics.py` ``` def __init__(self, problem: Problem, options: dict[str, Any] | None = None): """Initializer for the persistent solver. Args: problem (Problem): The problem for the solver. options (dict[str,any]): Dictionary of parameters to set. What these should be depends on the solver used. """ self.problem = problem ``` #### solve ``` solve(target: str) -> SolverResults ``` Solves the current problem with the specified target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | a str representing the symbol of the target function. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ------------------------- | | `SolverResults` | `SolverResults` | The results of the solver | Source code in `desdeo/tools/generics.py` ``` @abstractmethod def solve(self, target: str) -> SolverResults: """Solves the current problem with the specified target. Args: target (str): a str representing the symbol of the target function. Returns: SolverResults: The results of the solver """ ``` ### EMOResult Bases: `BaseModel` Defines a schema for a dataclass to store the results of an EMO method. Source code in `desdeo/tools/generics.py` ``` class EMOResult(BaseModel): """Defines a schema for a dataclass to store the results of an EMO method.""" model_config = ConfigDict(arbitrary_types_allowed=True, use_attribute_docstrings=True) optimal_variables: pl.DataFrame = Field() """The decision vectors of the final population.""" optimal_outputs: pl.DataFrame = Field() """The objective vectors, constraint vectors, extra_funcs, and targets of the final population.""" @field_serializer("optimal_variables") def _serialize_optimal_variables(self, value: pl.DataFrame) -> dict[str, list[int | float]]: return value.to_dict(as_series=False) @field_serializer("optimal_outputs") def _serialize_optimal_outputs(self, value: pl.DataFrame) -> dict[str, list[int | float]]: return value.to_dict(as_series=False) ``` #### optimal_outputs ``` optimal_outputs: DataFrame = Field() ``` The objective vectors, constraint vectors, extra_funcs, and targets of the final population. #### optimal_variables ``` optimal_variables: DataFrame = Field() ``` The decision vectors of the final population. ### PersistentSolver Defines a schema for a persistent solver class. Can be used when reinitializing the solver every time the problem is changed is not practical. Source code in `desdeo/tools/generics.py` ``` class PersistentSolver: """Defines a schema for a persistent solver class. Can be used when reinitializing the solver every time the problem is changed is not practical. """ evaluator: object problem: Problem def __init__(self, problem: Problem, options: dict[str, Any] | None = None): """Initializer for the persistent solver. Args: problem (Problem): The problem for the solver. options (dict[str,any]): Dictionary of parameters to set. What these should be depends on the solver used. """ self.problem = problem def add_constraint(self, constraint: Constraint | list[Constraint]): """Add a constraint expression to the solver. Args: constraint (Constraint): the constraint function expression. """ def add_objective(self, objective: Objective): """Adds an objective function expression to the solver. Args: objective (Objective): an objective function expression to be added. """ def add_scalarization_function(self, scalarization: ScalarizationFunction): """Adds a scalrization expression to the solver. Args: scalarization (ScalarizationFunction): A scalarization function to be added. """ def add_variable(self, variable: Variable): """Add a variable to the solver. Args: variable (Variable): The definition of the variable to be added. """ def remove_constraint(self, symbol: str): """Removes a constraint from the solver. Args: symbol (str): a str representing the symbol of the constraint to be removed. """ def remove_variable(self, symbol: str): """Removes a variable from the model. Args: symbol (str): a str representing the symbol of the variable to be removed. """ def solve(self, target: str) -> SolverResults | None: """Solves the current problem with the specified target. Args: target (str): a str representing the symbol of the target function. Returns: SolverResults: The results of the solver """ ``` #### __init__ ``` __init__( problem: Problem, options: dict[str, Any] | None = None ) ``` Initializer for the persistent solver. Parameters: | Name | Type | Description | Default | | --------- | ---------------- | --------------------------------------------------------------------------------- | ---------- | | `problem` | `Problem` | The problem for the solver. | *required* | | `options` | `dict[str, any]` | Dictionary of parameters to set. What these should be depends on the solver used. | `None` | Source code in `desdeo/tools/generics.py` ``` def __init__(self, problem: Problem, options: dict[str, Any] | None = None): """Initializer for the persistent solver. Args: problem (Problem): The problem for the solver. options (dict[str,any]): Dictionary of parameters to set. What these should be depends on the solver used. """ self.problem = problem ``` #### add_constraint ``` add_constraint(constraint: Constraint | list[Constraint]) ``` Add a constraint expression to the solver. Parameters: | Name | Type | Description | Default | | ------------ | ------------ | ----------------------------------- | ---------- | | `constraint` | `Constraint` | the constraint function expression. | *required* | Source code in `desdeo/tools/generics.py` ``` def add_constraint(self, constraint: Constraint | list[Constraint]): """Add a constraint expression to the solver. Args: constraint (Constraint): the constraint function expression. """ ``` #### add_objective ``` add_objective(objective: Objective) ``` Adds an objective function expression to the solver. Parameters: | Name | Type | Description | Default | | ----------- | ----------- | --------------------------------------------- | ---------- | | `objective` | `Objective` | an objective function expression to be added. | *required* | Source code in `desdeo/tools/generics.py` ``` def add_objective(self, objective: Objective): """Adds an objective function expression to the solver. Args: objective (Objective): an objective function expression to be added. """ ``` #### add_scalarization_function ``` add_scalarization_function( scalarization: ScalarizationFunction, ) ``` Adds a scalrization expression to the solver. Parameters: | Name | Type | Description | Default | | --------------- | ----------------------- | ------------------------------------- | ---------- | | `scalarization` | `ScalarizationFunction` | A scalarization function to be added. | *required* | Source code in `desdeo/tools/generics.py` ``` def add_scalarization_function(self, scalarization: ScalarizationFunction): """Adds a scalrization expression to the solver. Args: scalarization (ScalarizationFunction): A scalarization function to be added. """ ``` #### add_variable ``` add_variable(variable: Variable) ``` Add a variable to the solver. Parameters: | Name | Type | Description | Default | | ---------- | ---------- | ------------------------------------------- | ---------- | | `variable` | `Variable` | The definition of the variable to be added. | *required* | Source code in `desdeo/tools/generics.py` ``` def add_variable(self, variable: Variable): """Add a variable to the solver. Args: variable (Variable): The definition of the variable to be added. """ ``` #### remove_constraint ``` remove_constraint(symbol: str) ``` Removes a constraint from the solver. Parameters: | Name | Type | Description | Default | | -------- | ----- | -------------------------------------------------------------- | ---------- | | `symbol` | `str` | a str representing the symbol of the constraint to be removed. | *required* | Source code in `desdeo/tools/generics.py` ``` def remove_constraint(self, symbol: str): """Removes a constraint from the solver. Args: symbol (str): a str representing the symbol of the constraint to be removed. """ ``` #### remove_variable ``` remove_variable(symbol: str) ``` Removes a variable from the model. Parameters: | Name | Type | Description | Default | | -------- | ----- | ------------------------------------------------------------ | ---------- | | `symbol` | `str` | a str representing the symbol of the variable to be removed. | *required* | Source code in `desdeo/tools/generics.py` ``` def remove_variable(self, symbol: str): """Removes a variable from the model. Args: symbol (str): a str representing the symbol of the variable to be removed. """ ``` #### solve ``` solve(target: str) -> SolverResults | None ``` Solves the current problem with the specified target. Parameters: | Name | Type | Description | Default | | -------- | ----- | ----------------------------------------------------- | ---------- | | `target` | `str` | a str representing the symbol of the target function. | *required* | Returns: | Name | Type | Description | | --------------- | --------------- | ----------- | | `SolverResults` | \`SolverResults | None\` | Source code in `desdeo/tools/generics.py` ``` def solve(self, target: str) -> SolverResults | None: """Solves the current problem with the specified target. Args: target (str): a str representing the symbol of the target function. Returns: SolverResults: The results of the solver """ ``` ### SolverError Bases: `Exception` Raised when an error with a solver is encountered. Source code in `desdeo/tools/generics.py` ``` class SolverError(Exception): """Raised when an error with a solver is encountered.""" ``` ### SolverResults Bases: `BaseModel` Defines a schema for a dataclass to store the results of a solver. Source code in `desdeo/tools/generics.py` ``` class SolverResults(BaseModel): """Defines a schema for a dataclass to store the results of a solver.""" optimal_variables: dict[str, int | float | list] = Field(description="The optimal decision variables found.") optimal_objectives: dict[str, float | list[float]] = Field( description="The objective function values corresponding to the optimal decision variables found." ) constraint_values: dict[str, float | int | list[float] | list] | None | Any = Field( description=( "The constraint values of the problem. A negative value means the constraint is respected, " "a positive one means it has been breached." ), default=None, ) extra_func_values: dict[str, float | list[float]] | None = Field( description=("The extra function values of the problem."), default=None ) scalarization_values: dict[str, float | list[float]] | None = Field( description=("The scalarization function values of the problem."), default=None ) lagrange_multipliers: dict[str, float | list[float]] | None = Field( description="The Lagrange multipliers of the problem.", default=None ) success: bool = Field(description="A boolean flag indicating whether the optimization was successful or not.") message: str = Field(description="Description of the cause of termination.") ``` ## SCORE Bands Use the auto_SCORE function to generate the SCORE bands visualization. This module contains the functions which generate SCORE bands visualizations. It also contains functions to calculate the order and positions of the objective axes, as well as a heatmap of correlation matrix. To run the SCORE bands visualization, use the `score_json` function to generate the data for the visualization, and then use the `plot_score` function to generate the figure. You can also pass the result of `score_json` to other frontends for visualization. ### CustomClusterOptions Bases: `BaseModel` Options for custom clustering provided by the user. Source code in `desdeo/tools/score_bands.py` ``` class CustomClusterOptions(BaseModel): """Options for custom clustering provided by the user.""" model_config = ConfigDict(use_attribute_docstrings=True) name: str = Field(default="Custom") """Custom user-provided clusters.""" clusters: list[int] """List of cluster IDs (one for each solution) indicating the cluster to which each solution belongs.""" ``` #### clusters ``` clusters: list[int] ``` List of cluster IDs (one for each solution) indicating the cluster to which each solution belongs. #### name ``` name: str = Field(default='Custom') ``` Custom user-provided clusters. ### DBSCANOptions Bases: `BaseModel` Options for DBSCAN clustering algorithm. Source code in `desdeo/tools/score_bands.py` ``` class DBSCANOptions(BaseModel): """Options for DBSCAN clustering algorithm.""" model_config = ConfigDict(use_attribute_docstrings=True) name: str = Field(default="DBSCAN") """DBSCAN clustering algorithm.""" ``` #### name ``` name: str = Field(default='DBSCAN') ``` DBSCAN clustering algorithm. ### DimensionClusterOptions Bases: `BaseModel` Options for clustering by one of the objectives/decision variables. Source code in `desdeo/tools/score_bands.py` ``` class DimensionClusterOptions(BaseModel): """Options for clustering by one of the objectives/decision variables.""" model_config = ConfigDict(use_attribute_docstrings=True) name: str = Field(default="DimensionCluster") """Clustering by one of the dimensions.""" dimension_name: str """Dimension to use for clustering.""" n_clusters: int = Field(default=5) """Number of clusters to use. Defaults to 5.""" kind: Literal["EqualWidth", "EqualFrequency"] = Field(default="EqualWidth") """Kind of clustering to use. Either "EqualWidth", which divides the dimension range into equal width intervals, or "EqualFrequency", which divides the dimension values into intervals with equal number of solutions. Defaults to "EqualWidth".""" ``` #### dimension_name ``` dimension_name: str ``` Dimension to use for clustering. #### kind ``` kind: Literal["EqualWidth", "EqualFrequency"] = Field( default="EqualWidth" ) ``` Kind of clustering to use. Either "EqualWidth", which divides the dimension range into equal width intervals, or "EqualFrequency", which divides the dimension values into intervals with equal number of solutions. Defaults to "EqualWidth". #### n_clusters ``` n_clusters: int = Field(default=5) ``` Number of clusters to use. Defaults to 5. #### name ``` name: str = Field(default='DimensionCluster') ``` Clustering by one of the dimensions. ### DistanceFormula Bases: `int`, `Enum` Distance formulas supported by SCORE bands. See the paper for details. Source code in `desdeo/tools/score_bands.py` ``` class DistanceFormula(int, Enum): """Distance formulas supported by SCORE bands. See the paper for details.""" FORMULA_1 = 1 FORMULA_2 = 2 ``` ### GMMOptions Bases: `BaseModel` Options for Gaussian Mixture Model clustering algorithm. Source code in `desdeo/tools/score_bands.py` ``` class GMMOptions(BaseModel): """Options for Gaussian Mixture Model clustering algorithm.""" model_config = ConfigDict(use_attribute_docstrings=True) name: str = Field(default="GMM") """Gaussian Mixture Model clustering algorithm.""" scoring_method: Literal["BIC", "silhouette"] = Field(default="silhouette") """Scoring method to use for GMM. Either "BIC" or "silhouette". Defaults to "silhouette". This option determines how the number of clusters is chosen.""" ``` #### name ``` name: str = Field(default='GMM') ``` Gaussian Mixture Model clustering algorithm. #### scoring_method ``` scoring_method: Literal["BIC", "silhouette"] = Field( default="silhouette" ) ``` Scoring method to use for GMM. Either "BIC" or "silhouette". Defaults to "silhouette". This option determines how the number of clusters is chosen. ### KMeansOptions Bases: `BaseModel` Options for KMeans clustering algorithm. Source code in `desdeo/tools/score_bands.py` ``` class KMeansOptions(BaseModel): """Options for KMeans clustering algorithm.""" model_config = ConfigDict(use_attribute_docstrings=True) name: str = Field(default="KMeans") """KMeans clustering algorithm.""" n_clusters: int = Field(default=5) """Number of clusters to use. Defaults to 5.""" ``` #### n_clusters ``` n_clusters: int = Field(default=5) ``` Number of clusters to use. Defaults to 5. #### name ``` name: str = Field(default='KMeans') ``` KMeans clustering algorithm. ### SCOREBandsConfig Bases: `BaseModel` Configuration options for SCORE bands visualization. Source code in `desdeo/tools/score_bands.py` ``` class SCOREBandsConfig(BaseModel): """Configuration options for SCORE bands visualization.""" model_config = ConfigDict(use_attribute_docstrings=True) dimensions: list[str] | None = Field(default=None) """List of variable/objective names (i.e., column names in the data) to include in the visualization. If None, all columns in the data are used. Defaults to None.""" descriptive_names: dict[str, str] | None = Field(default=None) """Optional dictionary mapping dimensions to descriptive names for display in the visualization. If None, the original dimension names are used. Defaults to None.""" units: dict[str, str] | None = Field(default=None) """Optional dictionary mapping dimensions to their units for display in the visualization. If None, no units are displayed. Defaults to None.""" axis_positions: dict[str, float] | None = Field(default=None) """Dictionary mapping objective names to their positions on the axes in the SCORE bands visualization. The first objective is at position 0.0, and the last objective is at position 1.0. Use this option if you want to manually set the axis positions. If None, the axis positions are calculated automatically based on correlations. Defaults to None.""" axis_colours: dict[str, str] | None = Field(default=None) """Optional dictionary to set the colour of the axes corresponding to each objective. The keys should be the same as in the 'dimensions' field. The values should be a valid plotly color string. Defaults to None. Valid plotly color strings include: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list """ highlight_cluster: int | None = Field(default=None) """Cluster ID to highlight in the visualization. If None, no cluster is highlighted. Defaults to None. If a cluster ID is provided, the corresponding cluster is highlighted in the visualization by having a pattern fill in the band. """ clustering_algorithm: ClusteringOptions = Field( default=DBSCANOptions(), ) """ Clustering algorithm to use. Currently supports one of `ClusteringOptions`. """ distance_formula: DistanceFormula = Field(default=DistanceFormula.FORMULA_1) """Distance formula to use. The value should be 1 or 2. Check the paper for details. Defaults to 1.""" distance_parameter: float = Field(default=0.05) """Change the relative distances between the objective axes. Increase this value if objectives are placed too close together. Decrease this value if the objectives are equidistant in a problem with objective clusters. Defaults to 0.05.""" use_absolute_correlations: bool = Field(default=False) """Whether to use absolute value of the correlation to calculate the placement of axes. Defaults to False.""" include_solutions: bool = Field(default=False) """Whether to include individual solutions. Defaults to False. If True, the size of the resulting figure may be very large for datasets with many solutions. Moreover, the individual traces are hidden by default, but can be viewed interactively in the figure.""" include_medians: bool = Field(default=False) """Whether to include cluster medians. Defaults to False. If True, the median traces are hidden by default, but can be viewed interactively in the figure.""" interval_size: float = Field(default=0.95) """The size (as a fraction) of the interval to use for the bands. Defaults to 0.95, meaning that 95% of the middle solutions in a cluster will be included in the band. The rest will be considered outliers.""" scales: dict[str, tuple[float, float]] | None = Field(default=None) """Optional dictionary specifying the min and max values for each objective. The keys should be the objective names (i.e., column names in the data), and the values should be tuples of (min, max). If not provided, the min and max will be calculated from the data.""" ``` #### axis_colours ``` axis_colours: dict[str, str] | None = Field(default=None) ``` Optional dictionary to set the colour of the axes corresponding to each objective. The keys should be the same as in the 'dimensions' field. The values should be a valid plotly color string. Defaults to None. Valid plotly color strings include - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list #### axis_positions ``` axis_positions: dict[str, float] | None = Field( default=None ) ``` Dictionary mapping objective names to their positions on the axes in the SCORE bands visualization. The first objective is at position 0.0, and the last objective is at position 1.0. Use this option if you want to manually set the axis positions. If None, the axis positions are calculated automatically based on correlations. Defaults to None. #### clustering_algorithm ``` clustering_algorithm: ClusteringOptions = Field( default=DBSCANOptions() ) ``` Clustering algorithm to use. Currently supports one of `ClusteringOptions`. #### descriptive_names ``` descriptive_names: dict[str, str] | None = Field( default=None ) ``` Optional dictionary mapping dimensions to descriptive names for display in the visualization. If None, the original dimension names are used. Defaults to None. #### dimensions ``` dimensions: list[str] | None = Field(default=None) ``` List of variable/objective names (i.e., column names in the data) to include in the visualization. If None, all columns in the data are used. Defaults to None. #### distance_formula ``` distance_formula: DistanceFormula = Field( default=DistanceFormula.FORMULA_1 ) ``` Distance formula to use. The value should be 1 or 2. Check the paper for details. Defaults to 1. #### distance_parameter ``` distance_parameter: float = Field(default=0.05) ``` Change the relative distances between the objective axes. Increase this value if objectives are placed too close together. Decrease this value if the objectives are equidistant in a problem with objective clusters. Defaults to 0.05. #### highlight_cluster ``` highlight_cluster: int | None = Field(default=None) ``` Cluster ID to highlight in the visualization. If None, no cluster is highlighted. Defaults to None. If a cluster ID is provided, the corresponding cluster is highlighted in the visualization by having a pattern fill in the band. #### include_medians ``` include_medians: bool = Field(default=False) ``` Whether to include cluster medians. Defaults to False. If True, the median traces are hidden by default, but can be viewed interactively in the figure. #### include_solutions ``` include_solutions: bool = Field(default=False) ``` Whether to include individual solutions. Defaults to False. If True, the size of the resulting figure may be very large for datasets with many solutions. Moreover, the individual traces are hidden by default, but can be viewed interactively in the figure. #### interval_size ``` interval_size: float = Field(default=0.95) ``` The size (as a fraction) of the interval to use for the bands. Defaults to 0.95, meaning that 95% of the middle solutions in a cluster will be included in the band. The rest will be considered outliers. #### scales ``` scales: dict[str, tuple[float, float]] | None = Field( default=None ) ``` Optional dictionary specifying the min and max values for each objective. The keys should be the objective names (i.e., column names in the data), and the values should be tuples of (min, max). If not provided, the min and max will be calculated from the data. #### units ``` units: dict[str, str] | None = Field(default=None) ``` Optional dictionary mapping dimensions to their units for display in the visualization. If None, no units are displayed. Defaults to None. #### use_absolute_correlations ``` use_absolute_correlations: bool = Field(default=False) ``` Whether to use absolute value of the correlation to calculate the placement of axes. Defaults to False. ### SCOREBandsResult Bases: `BaseModel` Pydantic/JSON model for representing SCORE Bands. Source code in `desdeo/tools/score_bands.py` ``` class SCOREBandsResult(BaseModel): """Pydantic/JSON model for representing SCORE Bands.""" model_config = ConfigDict(use_attribute_docstrings=True) options: SCOREBandsConfig """Configuration options used to generate the SCORE bands.""" ordered_dimensions: list[str] """List of variable/objective names (i.e., column names in the data). Ordered according to their placement in the SCORE bands visualization.""" clusters: list[int] """List of cluster IDs (one for each solution) indicating the cluster to which each solution belongs.""" cluster_names: dict[int, str] | None = Field(default=None) """Optional dictionary mapping cluster IDs to descriptive names for display in the visualization. If None, the cluster IDs themselves are used as names. Defaults to None.""" cluster_hover_info: dict[int, str] | None = Field(default=None) """Optional dictionary mapping cluster IDs to hover information for display in the visualization. If None, no additional hover information is displayed. Defaults to None.""" cluster_extremes: dict[int, dict[str, tuple[float, float]]] """Map cluster IDs to dictionaries of objective names and their corresponding extreme values (min, max).""" axis_positions: dict[str, float] """Dictionary mapping objective names to their positions on the axes in the SCORE bands visualization. The first objective is at position 0.0, and the last objective is at position 1.0.""" bands: dict[int, dict[str, tuple[float, float]]] """Dictionary mapping cluster IDs to dictionaries of objective names and their corresponding band extremes (min, max).""" medians: dict[int, dict[str, float]] """Dictionary mapping cluster IDs to dictionaries of objective names and their corresponding median values.""" cardinalities: dict[int, int] """Dictionary mapping cluster IDs to the number of solutions in each cluster.""" ``` #### axis_positions ``` axis_positions: dict[str, float] ``` Dictionary mapping objective names to their positions on the axes in the SCORE bands visualization. The first objective is at position 0.0, and the last objective is at position 1.0. #### bands ``` bands: dict[int, dict[str, tuple[float, float]]] ``` Dictionary mapping cluster IDs to dictionaries of objective names and their corresponding band extremes (min, max). #### cardinalities ``` cardinalities: dict[int, int] ``` Dictionary mapping cluster IDs to the number of solutions in each cluster. #### cluster_extremes ``` cluster_extremes: dict[int, dict[str, tuple[float, float]]] ``` Map cluster IDs to dictionaries of objective names and their corresponding extreme values (min, max). #### cluster_hover_info ``` cluster_hover_info: dict[int, str] | None = Field( default=None ) ``` Optional dictionary mapping cluster IDs to hover information for display in the visualization. If None, no additional hover information is displayed. Defaults to None. #### cluster_names ``` cluster_names: dict[int, str] | None = Field(default=None) ``` Optional dictionary mapping cluster IDs to descriptive names for display in the visualization. If None, the cluster IDs themselves are used as names. Defaults to None. #### clusters ``` clusters: list[int] ``` List of cluster IDs (one for each solution) indicating the cluster to which each solution belongs. #### medians ``` medians: dict[int, dict[str, float]] ``` Dictionary mapping cluster IDs to dictionaries of objective names and their corresponding median values. #### options ``` options: SCOREBandsConfig ``` Configuration options used to generate the SCORE bands. #### ordered_dimensions ``` ordered_dimensions: list[str] ``` List of variable/objective names (i.e., column names in the data). Ordered according to their placement in the SCORE bands visualization. ### \_DBSCANClustering ``` _DBSCANClustering(data: DataFrame) -> np.ndarray ``` Cluster the data using DBSCAN with silhouette scoring to choose eps. Source code in `desdeo/tools/score_bands.py` ``` def _DBSCANClustering(data: pl.DataFrame) -> np.ndarray: # noqa: N802 """Cluster the data using DBSCAN with silhouette scoring to choose eps.""" x = StandardScaler().fit_transform(data.to_numpy()) eps_options = np.linspace(0.01, 1, 20) best_score = -np.inf best_labels = np.ones(len(data)) for eps_option in eps_options: db = DBSCAN(eps=eps_option, min_samples=10, metric="cosine").fit(x) core_samples_mask = np.zeros_like(db.labels_, dtype=bool) core_samples_mask[db.core_sample_indices_] = True labels = db.labels_ try: score = silhouette_score(x, labels, metric="cosine") except ValueError: score = -np.inf if score > best_score: best_score = score best_labels = labels # print((best_score, chosen_eps)) return best_labels ``` ### \_gaussianmixtureclusteringwithBIC ``` _gaussianmixtureclusteringwithBIC( data: DataFrame, ) -> np.ndarray ``` Cluster the data using Gaussian Mixture Model with BIC scoring. Source code in `desdeo/tools/score_bands.py` ``` def _gaussianmixtureclusteringwithBIC(data: pl.DataFrame) -> np.ndarray: # noqa: N802 """Cluster the data using Gaussian Mixture Model with BIC scoring.""" data_copy = data.to_numpy() data_copy = StandardScaler().fit_transform(data_copy) lowest_bic = np.inf bic = [] n_components_range = range(1, min(11, len(data_copy))) cv_types: list[Literal["full", "tied", "diag", "spherical"]] = ["spherical", "tied", "diag", "full"] for cv_type in cv_types: for n_components in n_components_range: # Fit a Gaussian mixture with EM gmm = GaussianMixture(n_components=n_components, covariance_type=cv_type) gmm.fit(data_copy) bic.append(gmm.score(data_copy)) # bic.append(gmm.bic(data)) if bic[-1] < lowest_bic: lowest_bic = bic[-1] best_gmm = gmm return best_gmm.predict(data_copy) ``` ### \_gaussianmixtureclusteringwithsilhouette ``` _gaussianmixtureclusteringwithsilhouette( data: DataFrame, ) -> np.ndarray ``` Cluster the data using Gaussian Mixture Model with silhouette scoring. Source code in `desdeo/tools/score_bands.py` ``` def _gaussianmixtureclusteringwithsilhouette(data: pl.DataFrame) -> np.ndarray: """Cluster the data using Gaussian Mixture Model with silhouette scoring.""" x = StandardScaler().fit_transform(data.to_numpy()) best_score = -np.inf best_labels = np.ones(len(data)) n_components_range = range(1, min(11, len(data))) cv_types: list[Literal["full", "tied", "diag", "spherical"]] = ["spherical", "tied", "diag", "full"] for cv_type in cv_types: for n_components in n_components_range: # Fit a Gaussian mixture with EM gmm = GaussianMixture(n_components=n_components, covariance_type=cv_type) labels = gmm.fit_predict(x) try: score = silhouette_score(x, labels, metric="cosine") except ValueError: score = -np.inf if score > best_score: best_score = score best_labels = labels # print(best_score) return best_labels ``` ### annotated_heatmap ``` annotated_heatmap( correlation_matrix: ndarray, col_names: list, order: list | ndarray, ) -> go.Figure ``` Create a heatmap of the correlation matrix. Probably should be named something else. Parameters: | Name | Type | Description | Default | | -------------------- | ---------------------- | ------------------------------------------------------------------- | ---------- | | `correlation_matrix` | `ndarray` | 2-D square array of correlation values between pairs of objectives. | *required* | | `col_names` | `List` | Objective names. | *required* | | `order` | `Union[List, ndarray]` | Order in which the objectives are shown in SCORE bands. | *required* | Returns: | Type | Description | | -------- | ---------------------- | | `Figure` | go.Figure: The heatmap | Source code in `desdeo/tools/score_bands.py` ``` def annotated_heatmap(correlation_matrix: np.ndarray, col_names: list, order: list | np.ndarray) -> go.Figure: """Create a heatmap of the correlation matrix. Probably should be named something else. Args: correlation_matrix (np.ndarray): 2-D square array of correlation values between pairs of objectives. col_names (List): Objective names. order (Union[List, np.ndarray]): Order in which the objectives are shown in SCORE bands. Returns: go.Figure: The heatmap """ corr = pl.DataFrame(correlation_matrix, index=col_names, columns=col_names) corr = corr[col_names[order]].loc[col_names[order[::-1]]] corr = np.rint(corr * 100) / 100 # Take upto two significant figures only to make heatmap readable. fig = ff.create_annotated_heatmap( corr.to_numpy(), x=list(corr.columns), y=list(corr.index), annotation_text=corr.astype(str).to_numpy(), ) fig.update_layout(title="Pearson correlation coefficients") return fig ``` ### calculate_axes_positions ``` calculate_axes_positions( dimension_order: list[int], corr: ndarray, dist_parameter: float, distance_formula: DistanceFormula = DistanceFormula.FORMULA_1, ) -> np.ndarray ``` Calculate the position of the axes for the SCORE bands visualization based on correlations. Parameters: | Name | Type | Description | Default | | ------------------ | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | `dimension_order` | `list[int]` | Order of the variables to be plotted. | *required* | | `corr` | `ndarray` | Correlation (pearson) matrix. | *required* | | `dist_parameter` | `float` | Change the relative distances between the axes. Increase this value if the axes are placed too close together. Decrease this value if the axes are equidistant. | *required* | | `distance_formula` | `DistanceFormula` | The value should be 1 or 2. Check the paper for details. Defaults to DistanceFormula.FORMULA_1. | `FORMULA_1` | Returns: | Type | Description | | --------- | ------------------------------------------------------ | | `ndarray` | np.ndarray: Positions of the axes in the range [0, 1]. | Source code in `desdeo/tools/score_bands.py` ``` def calculate_axes_positions( dimension_order: list[int], corr: np.ndarray, dist_parameter: float, distance_formula: DistanceFormula = DistanceFormula.FORMULA_1, ) -> np.ndarray: """Calculate the position of the axes for the SCORE bands visualization based on correlations. Args: dimension_order (list[int]): Order of the variables to be plotted. corr (np.ndarray): Correlation (pearson) matrix. dist_parameter (float): Change the relative distances between the axes. Increase this value if the axes are placed too close together. Decrease this value if the axes are equidistant. distance_formula (DistanceFormula, optional): The value should be 1 or 2. Check the paper for details. Defaults to DistanceFormula.FORMULA_1. Returns: np.ndarray: Positions of the axes in the range [0, 1]. """ # axes positions order = np.asarray(list(itertools.pairwise(dimension_order))) axis_len = corr[order[:, 0], order[:, 1]] if distance_formula == DistanceFormula.FORMULA_1: axis_len = 1 - axis_len elif distance_formula == DistanceFormula.FORMULA_2: axis_len = 1 / (np.abs(axis_len) + 1) # Reciprocal for reverse else: # Should never reach here raise ValueError("distance_formula should be either 1 or 2 (int)") axis_len = axis_len + dist_parameter axis_len = axis_len / sum(axis_len) return np.cumsum(np.append(0, axis_len)) ``` ### cluster ``` cluster( data: DataFrame, options: ClusteringOptions ) -> np.ndarray ``` Cluster the data using the specified clustering algorithm and options. Source code in `desdeo/tools/score_bands.py` ``` def cluster(data: pl.DataFrame, options: ClusteringOptions) -> np.ndarray: """Cluster the data using the specified clustering algorithm and options.""" if isinstance(options, DimensionClusterOptions): return cluster_by_dimension(data, options) if isinstance(options, KMeansOptions): x = StandardScaler().fit_transform(data.to_numpy()) kmeans = KMeans(n_clusters=options.n_clusters, random_state=0).fit(x) return kmeans.labels_ if isinstance(options, DBSCANOptions): return _DBSCANClustering(data) if isinstance(options, GMMOptions): if options.scoring_method == "silhouette": return _gaussianmixtureclusteringwithsilhouette(data) if options.scoring_method == "BIC": return _gaussianmixtureclusteringwithBIC(data) if isinstance(options, CustomClusterOptions): if len(options.clusters) != len(data): raise ValueError("Length of custom clusters must match number of solutions in data.") return np.array(options.clusters) raise ValueError(f"Unknown clustering algorithm: {options}") ``` ### cluster_by_dimension ``` cluster_by_dimension( data: DataFrame, options: DimensionClusterOptions ) -> np.ndarray ``` Cluster the data by a specific dimension. Source code in `desdeo/tools/score_bands.py` ``` def cluster_by_dimension(data: pl.DataFrame, options: DimensionClusterOptions) -> np.ndarray: """Cluster the data by a specific dimension.""" if options.dimension_name not in data.columns: raise ValueError(f"Objective '{options.dimension_name}' not found in data.") # Select the dimension column for clustering dimension = data[options.dimension_name] # Perform clustering based on the specified method if options.kind == "EqualWidth": min_val: float = dimension.min() max_val: float = dimension.max() SMALL_VALUE = 1e-8 # noqa: N806 thresholds = np.linspace( min_val * (1 - SMALL_VALUE), # Ensure the minimum value is included in the first cluster max_val * (1 + SMALL_VALUE), # Ensure the maximum value is included in the last cluster options.n_clusters + 1, ) return np.digitize(dimension.to_numpy(), thresholds) # Cluster IDs start at 1 if options.kind == "EqualFrequency": levels: list[float] = [dimension.quantile(i / options.n_clusters) for i in range(1, options.n_clusters)] thresholds = [-np.inf, *levels, np.inf] return np.digitize(dimension.to_numpy(), thresholds) # Cluster IDs start at 1 raise ValueError(f"Unknown clustering kind: {options.kind}") ``` ### order_dimensions ``` order_dimensions( data: DataFrame, use_absolute_corr: bool = False ) -> tuple[np.ndarray, list[int]] ``` Calculate the order of objectives. Also returns the correlation matrix. Parameters: | Name | Type | Description | Default | | ------------------- | ----------- | ---------------------------------------------------------------------------- | ---------- | | `data` | `DataFrame` | Data to be visualized. | *required* | | `use_absolute_corr` | `bool` | Use absolute value of the correlation to calculate order. Defaults to False. | `False` | Returns: | Name | Type | Description | | ------- | --------------------------- | ----------------------------------------------------------------------------------------------- | | `tuple` | `tuple[ndarray, list[int]]` | The first element is the correlation matrix. The second element is the order of the objectives. | Source code in `desdeo/tools/score_bands.py` ``` def order_dimensions(data: pl.DataFrame, use_absolute_corr: bool = False) -> tuple[np.ndarray, list[int]]: """Calculate the order of objectives. Also returns the correlation matrix. Args: data (pl.DataFrame): Data to be visualized. use_absolute_corr (bool, optional): Use absolute value of the correlation to calculate order. Defaults to False. Returns: tuple: The first element is the correlation matrix. The second element is the order of the objectives. """ # Calculating correlations # corr = spearmanr(data).correlation # Pearson's coeff is better than Spearmann's, in some cases corr = np.asarray( [ [pearsonr(data.to_numpy()[:, i], data.to_numpy()[:, j])[0] for j in range(len(data.columns))] for i in range(len(data.columns)) ] ) # axes order: solving TSP distances = corr if use_absolute_corr: distances = np.abs(distances) obj_order = solve_tsp(-distances) return corr, obj_order ``` ### plot_score ``` plot_score( data: DataFrame, result: SCOREBandsResult ) -> go.Figure ``` Generate the SCORE Bands figure from the SCOREBandsResult data. Parameters: | Name | Type | Description | Default | | -------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------- | ---------- | | `data` | `DataFrame` | Dataframe of objective values. The column names should be the objective names. Each row should be an objective vector. | *required* | | `result` | `SCOREBandsResult` | The result containing all relevant data for the SCORE bands visualization. | *required* | Returns: | Type | Description | | -------- | -------------------------------- | | `Figure` | go.Figure: The SCORE bands plot. | Source code in `desdeo/tools/score_bands.py` ``` def plot_score(data: pl.DataFrame, result: SCOREBandsResult) -> go.Figure: """Generate the SCORE Bands figure from the SCOREBandsResult data. Args: data (pl.DataFrame): Dataframe of objective values. The column names should be the objective names. Each row should be an objective vector. result (SCOREBandsResult): The result containing all relevant data for the SCORE bands visualization. Returns: go.Figure: The SCORE bands plot. """ # some constants for the figure, can be made configurable in the future if needed num_ticks = 6 # number of ticks to show on each axis max_dist_percent = 0.02 # Maximum distance between equidistant tick position vs a rounded tick position. column_names = result.ordered_dimensions clusters = np.sort(np.unique(result.clusters)) cluster_th = 8 # max number of clusters to use 'Accent' color map with, otherwise use 'tab20' colorscale = ( matplotlib.colormaps["Accent"].resampled(len(clusters)) if len(clusters) <= cluster_th else matplotlib.colormaps["tab20"].resampled(len(clusters)) ) if result.options.scales is None: raise ValueError("Scales must be provided in the SCOREBandsResult to plot the figure.") # Original scaling (not used in final version, but keeping for reference) # scaled_data = data.select((pl.all() - pl.all().min()) / (pl.all().max() - pl.all().min())) # Scaling with respect to the provided scales, which may not aling with the actual min and max in the data # (e.g. if user wants to use fixed scales across multiple visualizations) scaled_data = data.with_columns( [ (pl.col(col) - result.options.scales[col][0]) / (result.options.scales[col][1] - result.options.scales[col][0]) for col in column_names ] ) fig = go.Figure() fig.update_xaxes(showticklabels=False, showgrid=False, zeroline=False) fig.update_yaxes(showticklabels=False, showgrid=False, zeroline=False) fig.update_layout(plot_bgcolor="rgba(0,0,0,0)") cluster_column_name = "cluster" # Avoid overwriting existing column just in case data has a 'cluster' column if cluster_column_name in scaled_data.columns: cluster_column_name = "cluster_id" scaled_data = scaled_data.with_columns(pl.Series(cluster_column_name, result.clusters)) if result.options.descriptive_names is None: descriptive_names = {name: name for name in column_names} else: descriptive_names = result.options.descriptive_names units = dict.fromkeys(column_names, "") if result.options.units is None else result.options.units # Add axes for _, col_name in enumerate(column_names): # check if axis_colours is provided, otherwise use black current_axis_colour = "black" if result.options.axis_colours is not None and col_name in result.options.axis_colours: current_axis_colour = result.options.axis_colours[col_name] # Calculate "nice" tick positions and values label_text, heights = smart_axis_tick_placement( axis_min=result.options.scales[col_name][0], axis_max=result.options.scales[col_name][1], num_ticks=num_ticks, max_dist_percent=max_dist_percent, ) # Axis lines fig.add_scatter( x=[result.axis_positions[col_name]] * num_ticks, y=heights, text=label_text, textposition="middle left", mode="markers+lines+text", line={"color": current_axis_colour}, showlegend=False, hoverinfo="skip", zorder=100, ) # Objective Name name = descriptive_names[col_name] splits = name.split() # If the name is too long, add a line break at the second space if len(splits) > 2: # noqa: PLR2004 splits[2] = "
" + splits[2] name = " ".join(splits) fig.add_scatter( x=[result.axis_positions[col_name]], y=[1.20], text=f"{name}", textfont={"size": 20}, mode="text", showlegend=False, ) # Units fig.add_scatter( x=[result.axis_positions[col_name]], y=[1.10], text=f"{units[col_name]}", textfont={"size": 12}, mode="text", showlegend=False, ) # Add bands for cluster_id in sorted(result.bands.keys()): # The cluster numbering starts at 1. Plotly reads the red, green and blue of rgba() from 0 to 255, so the # colors are taken as bytes: matplotlib's default fractions would all draw as (nearly) black. r, g, b, _ = colorscale(cluster_id - 1, bytes=True) a = 0.6 highlight = None if result.options.highlight_cluster is not None and cluster_id == result.options.highlight_cluster: highlight = {"shape": "x"} hovertext = ( result.cluster_hover_info.get(cluster_id, f"Cluster {cluster_id}") if result.cluster_hover_info is not None else f"Cluster {cluster_id}" ) color_bands = f"rgba({r}, {g}, {b}, {a})" color_solutions = f"rgba({r}, {g}, {b}, 0.5)" # color_soln = f"rgba({r}, {g}, {b}, {a})" lows = [ (result.bands[cluster_id][col_name][0] - result.options.scales[col_name][0]) / (result.options.scales[col_name][1] - result.options.scales[col_name][0]) for col_name in column_names ] highs = [ (result.bands[cluster_id][col_name][1] - result.options.scales[col_name][0]) / (result.options.scales[col_name][1] - result.options.scales[col_name][0]) for col_name in column_names ] medians = [ (result.medians[cluster_id][col_name] - result.options.scales[col_name][0]) / (result.options.scales[col_name][1] - result.options.scales[col_name][0]) for col_name in column_names ] current_cluster_name = "Cluster " + str(cluster_id) if result.cluster_names is not None and cluster_id in result.cluster_names: current_cluster_name = result.cluster_names[cluster_id] fig.add_scatter( x=[result.axis_positions[col_name] for col_name in column_names], y=lows, line={"color": color_bands}, name=f"{int(100 * result.options.interval_size)}% band: {current_cluster_name}", mode="lines", legendgroup=f"{int(100 * result.options.interval_size)}% band: {current_cluster_name}", showlegend=True, line_shape="spline", hovertext=hovertext, hoverinfo="text", ) # upper bound of the band fig.add_scatter( x=[result.axis_positions[col_name] for col_name in column_names], y=highs, line={"color": color_bands}, name=f"{current_cluster_name}", fillcolor=color_bands, mode="lines", fillpattern=go.scatter.Fillpattern(highlight), legendgroup=f"{int(100 * result.options.interval_size)}% band: {current_cluster_name}", showlegend=False, line_shape="spline", fill="tonexty", hovertext=hovertext, hoverinfo="text", ) if result.options.include_medians: # median fig.add_scatter( x=[result.axis_positions[col_name] for col_name in column_names], y=medians, line={"color": color_bands}, name=f"Median: {current_cluster_name}", mode="lines+markers", marker={"line": {"color": "Black", "width": 2}}, legendgroup=f"Median: {current_cluster_name}", showlegend=True, ) # Drawing each solution as a single trace (like how it was done in the past) can make the figure very heavy # and make interactions (showing/hiding traces) very laggy. # Thus here, we draw all solutions in a cluster as a single trace. Basically we make a huge zig-zag trace for # each cluster. E.g. imagine two solutions with obj vals (1, 2, 3) and (4, 5, 6) on three objectives. These # become the y values in the parallel coordinates plot in this order (1, 2, 3, 6, 5, 4). Subsets of these points # which belong to the same solution are given the same hovertext if result.options.include_solutions: cluster_solutions = scaled_data.filter(pl.col(cluster_column_name) == cluster_id).select(column_names) x = [] y = [] ax_pos = [result.axis_positions[col_name] for col_name in column_names] hovertexts = [] rev_ax_pos = ax_pos[::-1] for i, row in enumerate(cluster_solutions.iter_rows()): if i % 2 == 0: x = x + ax_pos y = y + list(row) else: x = x + rev_ax_pos y = y + list(row)[::-1] # Scale values back to original scale for hovertext hovertext = [ ( f"{col}: " f"{ ( val * (result.options.scales[col][1] - result.options.scales[col][0]) + result.options.scales[col][0] ):.2f}
" ) for col, val in zip(column_names, row, strict=True) ] hovertext = "".join(hovertext) hovertext = [hovertext] * len(column_names) hovertexts = hovertexts + hovertext fig.add_scatter( x=x, y=y, line={"color": color_solutions, "width": 1}, name=f"{result.cardinalities[cluster_id]} Solutions: {current_cluster_name}", mode="lines", legendgroup=f"{result.cardinalities[cluster_id]} Solutions: {current_cluster_name}", hovertext=hovertexts, hoverinfo="text", hoveron="points+fills", showlegend=True, ) fig.update_layout(font_size=18) fig.update_layout(legend={"orientation": "h", "yanchor": "top"}) return fig ``` ### score_json ``` score_json( data: DataFrame, options: SCOREBandsConfig ) -> SCOREBandsResult ``` Generate the SCORE Bands data for a given dataset and configuration options. Parameters: | Name | Type | Description | Default | | --------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `data` | `DataFrame` | Dataframe of variable (decision or objective) values. The column names should be the names of the variables to be plotted. Each row should be a solution. | *required* | | `options` | `SCOREBandsConfig` | Configuration options for generating the SCORE bands. | *required* | Returns: | Name | Type | Description | | ------------------ | ------------------ | -------------------------------------------------------------------------- | | `SCOREBandsResult` | `SCOREBandsResult` | The result containing all relevant data for the SCORE bands visualization. | Source code in `desdeo/tools/score_bands.py` ``` def score_json(data: pl.DataFrame, options: SCOREBandsConfig) -> SCOREBandsResult: """Generate the SCORE Bands data for a given dataset and configuration options. Args: data (pl.DataFrame): Dataframe of variable (decision or objective) values. The column names should be the names of the variables to be plotted. Each row should be a solution. options (SCOREBandsConfig): Configuration options for generating the SCORE bands. Returns: SCOREBandsResult: The result containing all relevant data for the SCORE bands visualization. """ options = deepcopy(options) # Calculating correlations and axes positions if options.dimensions is None: options.dimensions = data.columns data_copy = data.select([pl.col(col) for col in options.dimensions]) if options.axis_positions is None: corr, dimension_order = order_dimensions(data_copy, use_absolute_corr=options.use_absolute_correlations) axis_dist = calculate_axes_positions( dimension_order, corr, dist_parameter=options.distance_parameter, distance_formula=options.distance_formula, ) ordered_dimension_names = [data_copy.columns[i] for i in dimension_order] axis_positions = {name: axis_dist[i] for i, name in enumerate(ordered_dimension_names)} else: axis_positions = options.axis_positions ordered_dimension_names = sorted(axis_positions.keys(), key=axis_positions.get) clusters = cluster(data_copy, options.clustering_algorithm) if min(clusters) <= 0: clusters = clusters - np.min(clusters) + 1 # translate minimum to 1. # some sanity check: check if all cluster IDs are contiguous integers starting at 1, ending at number of clusters unique_clusters = np.unique(clusters) max_cluster_id = max(clusters) if not all(i in unique_clusters for i in range(1, max_cluster_id + 1)): warn( """Cluster IDs are not contiguous integers starting at 1. This may cause issues with the color mapping in the visualization.""", category=UserWarning, stacklevel=2, ) cluster_column_name = "cluster" if cluster_column_name in data_copy.columns: cluster_column_name = "cluster_id" data_copy = data_copy.with_columns(pl.Series(cluster_column_name, clusters)) grouped = data_copy.group_by(cluster_column_name) min_percentile = (1 - options.interval_size) / 2 max_percentile = 1 - min_percentile mins = grouped.quantile(min_percentile) maxs = grouped.quantile(max_percentile) cluster_mins = grouped.min() cluster_maxs = grouped.max() medians = grouped.median() frequencies = grouped.len() bands_dict = { cluster_id: { col_name: ( mins.filter(pl.col(cluster_column_name) == cluster_id)[col_name][0], maxs.filter(pl.col(cluster_column_name) == cluster_id)[col_name][0], ) for col_name in ordered_dimension_names } for cluster_id in mins[cluster_column_name].to_list() } cluster_extremes_dict = { cluster_id: { col_name: ( cluster_mins.filter(pl.col(cluster_column_name) == cluster_id)[col_name][0], cluster_maxs.filter(pl.col(cluster_column_name) == cluster_id)[col_name][0], ) for col_name in ordered_dimension_names } for cluster_id in cluster_mins[cluster_column_name].to_list() } medians_dict = { cluster_id: { col_name: medians.filter(pl.col(cluster_column_name) == cluster_id)[col_name][0] for col_name in ordered_dimension_names } for cluster_id in medians[cluster_column_name].to_list() } frequencies_dict = { cluster_id: frequencies.filter(pl.col(cluster_column_name) == cluster_id)["len"][0] for cluster_id in frequencies[cluster_column_name].to_list() } if options.scales is None: scales: dict[str, tuple[float, float]] = { dimension: (data_copy[dimension].min(), data_copy[dimension].max()) for dimension in ordered_dimension_names } options.scales = scales return SCOREBandsResult( options=options, ordered_dimensions=ordered_dimension_names, clusters=clusters.tolist(), axis_positions=axis_positions, bands=bands_dict, medians=medians_dict, cluster_extremes=cluster_extremes_dict, cardinalities=frequencies_dict, ) ``` ### smart_axis_tick_placement ``` smart_axis_tick_placement( axis_min: float, axis_max: float, num_ticks: int, max_dist_percent: float, ) -> tuple[list[str], list[float]] ``` Calculate smart tick placement for the axes in the SCORE bands visualization. Source code in `desdeo/tools/score_bands.py` ``` def smart_axis_tick_placement( axis_min: float, axis_max: float, num_ticks: int, max_dist_percent: float ) -> tuple[list[str], list[float]]: """Calculate smart tick placement for the axes in the SCORE bands visualization.""" min_label_delta = 100 label_text = np.linspace(axis_min, axis_max, num_ticks) heights = [0.0] * num_ticks max_distance = (axis_max - axis_min) * max_dist_percent # Get a range of candidate tick values around each label_text value # and choose the one with the least number of significant digits for j in range(len(label_text)): if j == 0 or j == len(label_text) - 1: # skip rounding for the first and last labels to ensure they are exactly the min and max values continue label_max = label_text[j] + max_distance label_min = label_text[j] - max_distance # Find the closest "nice" number to label_text[j] within the range [label_min, label_max] # i.e., least number of significant digits # while still being within the max distance from the original label text value. label_delta = label_max - label_min # All calculations are done in integers so we multiply the label_min and label_max by a power of 10 # such that the label_delta is at least 100. multiplier = 1 while label_delta * multiplier < min_label_delta: multiplier *= 10 label_min = label_min * multiplier label_max = label_max * multiplier if label_max > 0: changing_point = label_max stable_point = label_min else: changing_point = label_min stable_point = label_max # Remove the least significant digits until the changing_point is too far from the original label_text value # then reverse one step back to get the final label value. This gives us a tick label within the max distance # from the original label_text value, but with as few significant digits as possible for better readability. divider = 1 while True: divider *= 10 if abs(int(changing_point / divider) * divider) < abs(stable_point): break divider = divider / 10 # reverse one step back label_text[j] = int(changing_point / divider) * divider / multiplier # Get the correct height for the label_text[j] value based on the original axis_min and axis_max values heights[j] = (label_text[j] - axis_min) / (axis_max - axis_min) heights[-1] = 1.0 # Ensure the last label is exactly at the max scale value label_text = [f"{label:.6g}" for label in label_text] return label_text, heights ``` # Explanation Explanations are understanding-oriented and are meant to help users understand how different aspects of the framework function. ## Core-logic - **[The problem format](https://desdeo.readthedocs.io/en/latest/explanation/problem_format/index.md):** Learn about how multiobjective optimization problems are modeled in DESDEO - **[Parsing and evaluation](https://desdeo.readthedocs.io/en/latest/explanation/parsing_and_evaluating/index.md):** Learn how the problem models are parsed and evaluated in DESDEO - **[Scalarization](https://desdeo.readthedocs.io/en/latest/explanation/scalarization/index.md):** Learn how problems are scalarized in DESDEO - **[Scalarization methods](https://desdeo.readthedocs.io/en/latest/explanation/scalarization_methods/index.md):** Learn about how scalarization methods are used in DESDEO - **[Simulator support](https://desdeo.readthedocs.io/en/latest/explanation/simulator_support/index.md):** Learn about simulator files and how to form them - **[Solvers](https://desdeo.readthedocs.io/en/latest/explanation/solvers/index.md):** Learn how DESDEO can be used to interface to different optimizers - **[Test problems](https://desdeo.readthedocs.io/en/latest/explanation/test_problems/index.md):** Learn about different test problems implemented in DESDEO - **[Evolutionary Algorithms in DESDEO](https://desdeo.readthedocs.io/en/latest/explanation/templates_and_pub_sub/index.md):** Learn about the implementation of evolutionary algorithms in DESDEO - **[Crossover operators](https://desdeo.readthedocs.io/en/latest/explanation/crossover_operators/index.md):** Learn how the available crossover operators differ, and what the offspring they generate actually look like - **[Pydantic Interface for Evolutionary Algorithms](https://desdeo.readthedocs.io/en/latest/explanation/pydantic_interface/index.md):** Learn about the Pydantic interface that acts as a configuration/abstraction layer for the EA components and templates in DESDEO - **[Scenarios](https://desdeo.readthedocs.io/en/latest/explanation/scenarios/index.md):** Learn about scenarios and scenario optimization tools implemented in DESDEO ## Web-API - **[Database models and schema](https://desdeo.readthedocs.io/en/latest/explanation/database_models_and_schema/index.md):** Learn about the logic behind the models and schema used in the web-API. - **[Group Decision Making and Websockets](https://desdeo.readthedocs.io/en/latest/explanation/group_decision_making_and_websockets/index.md):** Learn about how the Group Decision Making framework built into DESDEO works and how it utilizes websockets. # Database models and schema To interact with the underlying database in the DESDEO web-API, the [SQLModel](https://sqlmodel.tiangolo.com/) library is used. It can be thought of an abstraction that neatly combines [SQLAlchemy](https://www.sqlalchemy.org/) with [Pydantic](https://docs.pydantic.dev/latest/) models. What can initially feel confusing are the multiple SQLModels that are defined, at face-value, for most part same purpose in the web-API. Before going into details why things are structured as they are, we must understand the purposes of the web-API. **The main purposes of the web-API are:** 1. retrieve and store data from and to a database, and 1. handle HTTP requests from clients (e.g., the DESDEO web-GUI) through its endpoints. There are three types of SQLModels in the web-API, which serve the two listed main purposes. Serving the first purpose are **table models**, while the second purpose is served by **response and request models**. These models also define the **schema** of the data that is handled in various parts of the web-API. We will cover each in the following sections. Model vs schema A **model** represents data structures and logic within application code, including methods to interact with data, while a **schema** defines the structure and organization of data, whether in a database or in HTTP request/response formats. In the context of databases, models use schemas to map application data structures to database structures. For HTTP endpoints, schemas define the expected format of request and response data, ensuring that communication between client and server adheres to a predefined structure, while models handle the logic and processing of this data within the application. Here, we explain the main logic and purpose of these three types of models and the schema they define in DESDEO's web-API. ## Table models ### The model For the purpose of storing data in a database, we define **table models**. Table models are models that define the schema of data that we store in the database managed by the web-API. These can be identified by the `table=True` parameter given when defining new SQLModels. E.g.,in the class defining the model `User` in `desdeo/api/models/user.py`: ``` class User(UserBase, table=True): """The table model of an user stored in the database.""" id: int | None = Field(primary_key=True, default=None) password_hash: str = Field() role: UserRole = Field() group: str = Field(default="") active_session_id: int | None = Field(default=None) # Back populates archive: list["ArchiveEntryDB"] = Relationship(back_populates="user") preferences: list["PreferenceDB"] = Relationship(back_populates="user") problems: list["ProblemDB"] = Relationship(back_populates="user") sessions: list["InteractiveSessionDB"] = Relationship(back_populates="user") ``` Why `UserBase` Notice that `UserBase` is a class that inherits from the `SQLModel` class, i.e.: ``` class UserBase(SQLModel): """Base user model.""" username: str = Field(index=True) ``` but for now, we can think of `UserBase` to just be synonymous with `SQLModel` in the above example. We will return to the purpose of having something like `UserBase` when defining table models and other types of models later. To see what will be stored in the database in case of the table model `User`, we have defined multiple class variables with the `Field` class imported from SQLModel. We will refer to these just as **fields**. The fields of the `User` table model are `id` (the primary key, i.e.., unique identifier of a user), `password_hash` (the hashed password of a user), `role` (the role/privileges of a user), `group` (the group of a user), and `active_session_id` (the identifier of the currently active session of a user). Additionally, `User` has also the field `username`, which is derived from the parent class `UserBase`. To put this into the context of a database, we can think of the table model `User` as the **rows** in a database, while the fields listed above can be thought of the **columns**: | id | password_hash | role | group | active_session_id | | --- | ------------- | ----- | ------ | ----------------- | | 1 | abc123 | admin | group1 | 101 | | 2 | def456 | dm | group1 | 102 | | 3 | ghi789 | guest | group2 | NULL | In addition, we have also defined **relationships** with other table models in the database using the `Relationship` class imported from SQLModel. These relationships are `archive`, `preferences`, `problems`, and `sessions`. These table models will have a foreign key, which will have the value of the user's id the table model is related to. In the case of the listed relationships, the `User` model is the **parent** while `archive`, `preferences`, `problems` and `sessions` are its children. Notice that the `User` might have multiple children of the same type, e.g., `problem`. ### Storing table models to the database To store table models to a database, we first need to create an instance of the model. Continuing with the `User` model as an example, we can create an instance of the model as follows: ``` user_example = User( username="Decision maker", password_hash=get_password_hash("example_password"), role=UserRole.dm, group="example", ) ``` Notice that we did not have to supply an `id` since this being a primary key, will be created automatically once the `user_example` is added to the database. Because SQLModel utilizes Pydantic, our model is also validated when created, which means that the field values (which correspond to rows of the `User` table model) we supply, are checked for their correct type. To add `user_example` to a database, we need to have access to a **database session**, which allows us to interact with the database. In the web-API, this session is automatically made available in the context of HTTP endpoints, also known as routers. Assuming we do have a database session '`session`' available, we can add `user_example` to it: ``` session.add(example_user) session.commit() ``` The `session.add` method alone is not enough as it only *stages* the changes to the database in memory. To write the changes, we need to commit them by calling `session.commit`. This way we may stage multiple changes to the database in memory, e.g., when adding multiple new users, and then commit (write) the changes to the database at once. This can minimize costly and blocking I/O interactions with the database. How to get a database session? As mentioned, in the routers defined in the web-API, sessions are available automatically. In many of the functions that define endpoints, we will see the syntax `session: Annotated[Session, Depends(get_session)]` in the arguments. For instance: ``` @router.post("/solve") def solve_solutions( request: RPMSolveRequest, user: Annotated[User, Depends(get_current_user)], session: Annotated[Session, Depends(get_session)], ) -> RPMState: ... ``` Without going too much into details, it is enough to understand that each time an endpoint with such syntax is called, the value for the `session` argument is retrieved by calling the function `get_session`, which will yield a database session that can then be used to interact with the database. To see how a database session is created, the interested reader can refer to the file `desdeo/api/db.py`. The same principle applies in this example for the `user` argument as well, which is handled by the function `get_current_user`. ### Reading table models from a database To read existing table models from a database we will once again assume that a database session '`session`' is available. Assuming the `id` of `example_user` is `1`, we can retrieve `example_user` using the function `sqlmodel.select`: ``` statement = select(User).where(User.id == 1) user_from_db = session.exec(statement).first() ``` This is a fairly common pattern where we first define a query statement and then execute it to retrieve its results (query result) from the database. Notice that we passed the table model's class we wish to retrieve from the database to `select`, and then specified we want to select all users with their `id` value equal to 1. When executed, `session.exec` will return a list. Since we know that the `id` of each user is unique, at most one user will be returned (in this case `example_user`), so calling the method `first` on the query result is sufficient. If an user with `id=1` would have not existed, `None` would have been returned. Similarly, we could have queried the database for all users with the group `group1`: ``` statement = select(User).where(User.group == "group1") group1_users_from_db = session.exec(statement).all() ``` Now we have called the method `all` on the query result, which will either return `None` if no users in the database exist with `group="group1"`, or it will return a list of all the users (one or more) with `group="group1"`. Calling `first` like in the previous example would not make sense now, unless we specifically want the first user in the list. We could also get all users with `group="group1"` and `role="admin"`: ``` statement = select(User).where(User.group == "group1", User.role="admin") group1_admins = session.exec(statement).all() ``` Similarly, more refined queries with many more predicates can be formulated. Alternative syntax for retrieving data In the preceding examples we utilized `sqlmodel.select` to formulate queries. Alternatively, we could have also written ``` user_from_db = session.get(User, 1) ``` where the `get` method fetches the database entry of the table model `User` with the matching primary key, e.g., `id=1`. In fact, we could also use the SQLAlchemy version of `select` to query the database, but this is often more cumbersome than using `sqlmodel.select`, which is specifically for handling table models defined using SQLModel. However, for more advanced queries, SQLAlchemy can be used directly, and it can offer powerful tools in some cases. You can read more in the SQLAlchemy [Session API docs](https://docs.sqlalchemy.org/en/20/orm/session_api.html#session-api). ## Response and request models ### Response models In addition to table models, SQLModel is used to define so-called **response models**. These can be thought as a kind of *view* of a specific table model. Returning to the `User` example from the [table models section](#table-models), we have the response model `UserPublic` defined as: ``` class UserPublic(UserBase): """The object to handle public user information.""" id: int role: UserRole group: str ``` First, we note that the previously defined class argument `table` is now missing (it defaults to false), which means this is not a table model. `UserPublic` also derives from the previously seen `UserBase` class. Having a base class for the various models is a common design pattern in the web-API. Base classes are used to define fields that are common across the three kind of models in the web-API. They do not fall in any of the specific categories themselves (table model, response model, or request model); but are instead separate constructs to help define the other models. Second, we note that the fields in the response schema `UserPublic` consist of a sub-group of the attributes defined for `User`, namely, `id`, `role`, and `group`. The username is also available through the parent class `UserBase`. But what is the point of all of this? To understand the motivation for response models, let us consider the router `get_current_user_info`: ``` @router.get("/user_info") def get_current_user_info(user: Annotated[User, Depends(get_current_user)]) -> UserPublic: """Return information about the current user. Args: user (Annotated[User, Depends): user dependency, handled by `get_current_user`. Returns: UserPublic: public information about the current user. """ return user ``` As was the case with the database session, we get automatically the `user` defined as an argument to the endpoint through the function `get_current_user`. However, if we look at what `get_current_user` returns, it returns an object of type `User`, yet the endpoint `get_current_user` is supposed to return the response model `UserPublic`. What gives? What happens is that the `user` returned by `get_current_user` is used to instantiate a response model of type `UserPublic` when returned. In other words, we only grab the fields from the `user` object (which is of type `User`) that are present in `UserPublic`, and return those to the frontend application calling the web-API. Which is automagically handled by FastAPI, which is used to define the endpoints. The schema of the returned model will look like follows: ``` { "username": "string", "id": 0, "role": "guest", "group": "string" } ``` The above information is all the information we wish to return about the current user through the endpoint `get_current_user_info`, and that information is defined by the response model associated with the return type of the endpoint. This way we can exclude information, such as `password_hash`, which we might not wish to return to the client as part of the response provided for the current user. To put it simply, **we utilize response models to define what information we wish to return from the endpoints defined in the web-API.** We could define these models returned by each endpoint manually, but by utilizing response models, we can utilize already defined table models (and other SQLModels) instead, saving time and reducing the risk of introducing needless bugs. ### Request models The last type of model to be covered are **request models**. Unlike table models and response models, request models are used to define what information clients of the web-API need to provide when accessing each endpoint. For instance, the `solve_solutions` endpoint defined for the reference point method is defined as follows: ``` @router.post("/solve") def solve_solutions( request: RPMSolveRequest, user: Annotated[User, Depends(get_current_user)], session: Annotated[Session, Depends(get_session)], ) -> RPMState: ... ``` The content the client must explicitly provide is `request`, which is of type `RPMSolveRequest`. Looking at the definition of this **request model**: ``` class RPMSolveRequest(SQLModel): """Model of the request to the reference point method.""" problem_id: int session_id: int | None = Field(default=None) parent_state_id: int | None = Field(default=None) scalarization_options: dict[str, float | str | bool] | None = Field(sa_column=Column(JSON), default=None) solver: str | None = Field(default=None) solver_options: dict[str, float | str | bool] | None = Field(sa_column=Column(JSON), default=None) preference: ReferencePoint = Field(Column(JSON)) ``` we see that the endpoint expects a JSON object with the following schema: ``` { "problem_id": 0, "session_id": null, "parent_state_id": null, "scalarization_options": null, "solver": null, "solver_options": null, "preference": { "preference_type": "string", "aspiration_levels": {} } } ``` This simply means that request models are SQLModels that we define to specify what kind of data an endpoint expects when accessed. ## Wrapping things up To summarize, the three main type of model and their purpose in DESDEO's web-API are: - **table models**: used to define the schema of data stored in the database of the web-API, - **response models**: used to define the schema of data returned by the web-API's endpoints, and - **request models**: used to define the schema of data expected by the web-API's endpoints. This structure helps in separating concerns, making the codebase (hopefully!) more maintainable and easier to understand. The table models handle database operations, while the response and request models manage the data flow for HTTP interactions between the web-API and client applications. # Websockets and Group Decision Making This page documents how the Group Decision Making (GDM) framework built into DESDEO functions and how it utilizes websockets. This page also goes over how the functionality of this framework can be leveraged to create new GDM methods. For now, there is a functioning Group NIMBUS implementation, that we're going to be using as an example method to explain the concepts of this framework. In short, GNIMBUS is a group extension of the [NIMBUS](https://doi.org/10.1016/j.ejor.2004.07.052) method, in which a group articulates individual preferences, send them to the method and then vote for a solution. A useful tool for working with websockets is [Websocketking](https://websocketking.com/). It allows creating multiple connections, saving payloads and more. Once a user enters the page for the first time, a quick introduction should begin, going into further details. ## Notes on the implementation As with DESDEO in general, the endpoint routers and models used within are split into separate files. The relevant GDM models can be found at DESDEO/desdeo/api/models/gdm/gdm_base.py for the base classes and DESDEO/desdeo/api/models/gdm/gdm_aggregate.py for aggregation. Same goes for the routers. There's also method specific classes, as can be seen from DESDEO/desdeo/api/models/gdm/gnimbus.py for Group NIMBUS. The aggregation is split so that we can later on collect all possible methods and models to be used under one websocket endpoint. More on that later. ### The models and their relations The models within .../models/gdm/gdm_aggregate.py consists of a number of response and request models. The two most important models, however, are the table models; Group and GroupIteration. Group contains the information on the group and a link to the head group iteration. GroupIteration contains the information from iterations. ``` +-------------+ | | _______ ________v_______ | ________________ | Group | +---->| GroupIteration | +--+--->| GroupIteration | +-----> etc. |_______| | |----------------| | | |----------------| | | head ---+ | parent -----------+ | | parent -----------+ |_______| | child -----------+ | | child -----------+ | VotingPref | | | | OptimPref | | | VotingState | | | | OptimState | | |________________| | | |________________| | | | | None <------+ +-------------+----------+ ``` Here we can observe how Group holds link to the head GroupIteration, which then has links to its parents, which has links to its parent and so forth. The GroupIteration holds and stores the information on given preferences. It is essentially a dictionary with users' ids as keys and the corresponding preference as the value. These preferences are incomplete, and when all preferences are in, we start the process of optimizing/producing a solution corresponding to those preferences. The GroupIteration also has a connection to a State. The state is used to store the results and full preferences of the iteration: for example in above GNIMBUS case, it can hold information on how the users voted for specific solutions and what solution was chosen, or in optimization case, the reference points and what came out of those preference points. The corresponding States (VotingState, OptimizationState, EndState) are defined in ../models/state.py. As can be observed from .../models/gdm/gnimbus.py, there's a number of GNIMBUS specific classes. The most prominent of these are the Preference classes for storing the preferences when they are incomplete. There's also a number of response classes, and are used in similar manner as any other response classes with HTTP endpoints. ### The managers When the server is started, a singleton called ManagerManager that manages GroupManagers is spawned. Its responsibilities are to create and delete these GroupManagers. If a valid connection with an authorized user connects, ManagerManager checks whether a corresponding group/method already has a GroupManager and returns it. If there is no such GroupManager, it spawns it. Upon disconnection of a user, ManagerManager checks whether a GroupManager has any remaining connections. If there are none, the singleton deletes this GroupManager. A GroupManager handles the needs of a single group. These needs are handling connections, database accesses, message broadcasts, preference updates and optimization. Next, we'll go over relevant functions. The base for this manager can be found from .../api/routers/gdm/gdm_base.py. `def __init__(self, group_id: int)` Naturally, this is the constructor of the object. It checks that the group corresponding to the id exists. Then it initializes a dictionary for the users' websockets. `async def send_message(self, message: str, websocket: WebSocket)` Just sends single message through the specified websocket. `async def connect(self, user_id: int, websocket: WebSocket)` Attaches the websocket in the GroupManager's websocket dictionary. Also, if the previous iteration has any notifications that aren't sent, send notifications that the results are to be fetched. `async def disconnect(self, user_id: int, websocket: WebSocket)` Detaches the websocket object from the GroupManager's websocket dictionary. `async def broadcast(self, message: str)` Sends a message to all connected websockets. `async def notify(self, user_ids: list[int], message: str):` Notifies all users that are connected to the Manager. Returns a dict of who is notified and who is not. Those would be basic handling of connections and such. However, the difference between GroupManagers come from the "optimize" function and what happens within. `async def run_method(self, user_id: int, data: str)` This function is quite free form. There is the GNIMBUSManager to serve as an example in this case. In this function, the data is the raw data coming from websocket. That data will later be validated when we know what we want the data to be. Checks are performed to ensure that the necessary preliminary work has been done: GNIMBUS initialization has run, the wanted group exists, etc. When that is done, the execution of the function is diverged based on what is contained in the preferences class. Specifically, which method is used, in this case "optimization" or "voting" or "end". The implementation can be found at .../api/routers/gdm/gnimbus/gnimbus_manager.py. In these different paths, represented by the "optimization", "voting" and "ending" functions, we essentially: * Validate the preferences as either a ReferencePoint (e.g. `{"aspiration_levels": {"f_1": 0.4, "f_2": 0.7, "f_3": 0.1}}`) for optimization or a solution index (int) for voting or either true or false (coming in as something that can be cast to boolean) for ending the process. * Update the current GroupIteration's Preference field with the newest preferences. * If preferences from all members of the group are in, we can move on to result production (running GNIMBUS methods or voting for a result or ending for ending) * After those results are produced, the results and the preferences used to obtain those results are stored into States and that State is linked to the current GroupIteration. * Users are notified that the results are ready for fetching using separate HTTP endpoints. The notification information (as in who is notified and who is not) is stored to the iteration. * A new Preference item of the opposite type as the current type is created and returned from the path-specific function to the "run_method" function. Then a new GroupIteration is formed, with the newly created and returned Preference item contained within. Group's head iteration is updated to the newest iteration, the parent/child relations between the new and old GroupIteration are set. Now the new GroupIteration's Preference item is ready to be filled with preferences coming from the websocket. ### The websockets The websocket endpoint is found in ../routers/gdm/gdm_aggregate.py. The url for the websocket is `ws://[DOMAIN]:[PORT]/gdm/ws?token=[TOKEN]&group_id=[GROUP_ID]&method=[METHOD]`, where `[TOKEN]` is the token that is received from the API's `/login` endpoint, `[GROUP_ID]` is, naturally, the ID of the group the user is a member of and wants to work with and `[METHOD]` is the corresponding method the user wants to use, e.g. gnimbus. If the server is hosted on a server with TSL certificates etc. the appropriate protocol is `wss:`, similar to what is the case with `http:` and `https:`. When a user connects to this websocket, they are validated as a member of the group using `[TOKEN]` and `[GROUP_ID]` and then are connected to the Group's manager corresponding to `[METHOD]`. For as long as the user is connected to the websocket, they can send data over to the server. The data is validated as needed as described above (in the case of GNIMBUS). The users are also notified when optimization is done or if something goes wrong as a result of their actions. ### The routers These are just your standard HTTP endpoints. These can be used in general to manipulate groups and such. There's also the GNIMBUS specific endpoints used for fetching results and initializing the problem and such. ### Authors note after implementing the GDMScoreBands prototype The role of the websockets has been greatly diminished in the GDMSCOREBands implementation. Currently, the system rather utilizes HTTP endpoints to communicate with the Group Manager. Each HTTP endpoint has it's corresponding method in the group manager. In implementing the GDMSCOREBands system, it is evident that this system can be used to many degrees. One can, if they will, rely on the websockets for transferring preferences, messages, etc. and use the manager system to handle the optimization and so forth (as is done with GNIMBUS). One can also communicate with the manager through HTTPEndpoints, and implement the manager to handle the things (as is done with GDMSCOREBands). One could most likely also utilize the manager as a simple message system, making sure that the UI will fetch the right data from the right endpoint. In hindsight, the author of this system might have been blinded with the idea of websockets as a form of back-and-forth communication. The GNIMBUS system build on top of this works, yes, but it could have been simpler. A word forward: have the HTTP endpoints access the managers through import. Then have the endpoints utilize the manager's functionality. However, the groups and group iterations and their interplay is useful. # Pydantic Interface for Evolutionary Algorithms DESDEO implements many different evolutionary algorithm (EA) components (generators, genetic operators, etc.) and templates in which to use them, as explained in [Evolutionary Algorithms in DESDEO](https://desdeo.readthedocs.io/en/latest/explanation/templates_and_pub_sub/index.md). These components and templates can be used directly from Python code, as shown in the [Using Evolutionary Algorithms in DESDEO (Functional)](https://desdeo.readthedocs.io/en/latest/howtoguides/ea/index.md) guide. However, that approach may be cumbersome for certain use-cases, such as when using DESDEO from a web application or when configuring an optimization run from a configuration file or running DESDEO from other programming languages. To facilitate these use-cases, DESDEO provides a Pydantic-based (or JSON-schema-based) interface for configuring and running evolutionary algorithms. This interface allows users to define their [optimization problems](https://desdeo.readthedocs.io/en/latest/explanation/problem_format/index.md), algorithms, and parameters in a structured way, which can then be easily serialized to and from JSON or other formats. Essentially, the entire configuration of an evolutionary algorithm run can be represented as a Pydantic/JSON model, which can be validated and parsed by DESDEO. This makes it easier to set up and run optimization tasks without needing to write extensive Python code. For example, NSGA-III is represented as: ``` { "preference": null, "template": { "crossover": { "name": "SimulatedBinaryCrossover", "xover_probability": 0.5, "xover_distribution": 30.0 }, "mutation": { "name": "BoundedPolynomialMutation", "mutation_probability": null, "distribution_index": 20.0 }, "selection": { "name": "NSGA3Selector", "reference_vector_options": { ... // Options hidden for brevity }, "invert_reference_vectors": false }, "termination": { "name": "MaxGenerationsTerminator", "max_generations": 100 }, "generator": { "n_points": 100, "name": "LHSGenerator" }, "repair": { "name": "NoRepair" }, "use_archive": true, "seed": 42, "verbosity": 2, "algorithm_name": "NSGA3", "name": "Template1" } } ``` The above JSON snippet represents the configuration for an NSGA-III algorithm, including its genetic operators, selection method, termination criteria, and other parameters. Users can modify these parameters as needed and run the optimization from this configuration. The schema for these configurations is defined by the Pydantic model EMOOptions and can be exported to JSON Schema by calling the `EMOOptions.model_json_schema()` method. Examples of using this Pydantic interface can be found in the [Using Evolutionary Algorithms in DESDEO (Pydantic Interface)](https://desdeo.readthedocs.io/en/latest/howtoguides/ea_options/index.md) guide. # Scenarios [Download as Jupyter notebook](https://raw.githubusercontent.com/industrial-optimization-group/DESDEO/master/notebooks/scenarios.ipynb) One way of modeling uncertainty in decision making is using *scenarios*. A scenario in optimization context is typically a set of parameters or constraints that describes what our optimization problem might look like in a plausible future. In DESDEO scenarios are described by a [ScenarioModel](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.scenario.ScenarioModel). It contains base_problem that is a [Problem](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema) object. The base_problem is then modified by the different [Scenario](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.scenario.Scenario)s which are stored in a dict called scenarios. How different scenarios flow into one another is described by scenario_tree dict. The scenarios can also be assigned probabilities, which are stored in the scenario_probabilities dict. ## Building a ScenarioModel We will take a look at how a [ScenarioModel](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.scenario.ScenarioModel) is constructed with the help of an example. The first thing our ScenarioModel needs is a base_problem that will be modified by the different scenario. We will use the [summer_cabin_electricity](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.testproblems.summer_cabin_battery_problem) Problem as our base_problem. It is a MILP-problem with a few thousand variables. We will use the split version of the problem, where the decision variables relating to electricity usage have been split into three time periods. The reason for this will become apparent later. ``` from pprint import pprint from desdeo.problem.testproblems import summer_cabin_battery_problem_split base = summer_cabin_battery_problem_split(initial_soc=0, n_panels_max=50) pprint({i: base.objectives[i].name for i in range(len(base.objectives))}) ``` ``` {0: 'Electricity cost', 1: 'Investment cost'} ``` The problem is about choosing what kind of investments should be done in to the electricity supply of the summer cabin. The options are installing a battery with a capacity of 14-42 kWh or installing a number of solar panels that produce up to 160W of power each depending on the weather and the time of day. ### Defining scenarios The type of uncertainty we want to introduce is the possibility of losing the connection to the power grid because of a storm. We have two storms that each may or may not cause an electricity outage for 4 hours. To describe the scenarios arising from these possible events, we write a scenario_tree and put the scenario_probabilities in a dict. ``` scenario_tree = { "ROOT": ["S1", "S2"], "S1": ["S1a", "S1b"], "S2": ["S2a", "S2b"], "S1a": [], "S1b": [], "S2a": [], "S2b": [], } scenario_probabilities = { "S1": 0.9, "S2": 0.1, "S1a": 0.81, "S1b": 0.09, "S2a": 0.09, "S2b": 0.01, } # Including the leaf nodes in the scenario tree is optional, # so we can also define the scenario tree as follows: scenario_tree = { "ROOT": ["S1", "S2"], "S1": ["S1a", "S1b"], "S2": ["S2a", "S2b"], } ``` The `scenario_tree` is a dict, where the keys represent scenarios, and the values are lists that show which scenarios follow them. Leaf scenarios have an empty list, because there is no scenario following them. You can leave the leaf scenarios out of your scenario tree keys if you want. The tree above shows that first either scenario `S1` or `S2` happens. They can then be followed by second stage scenarios `S1a` or `S1b` and `S2a` or `S2b` respectively. If all of your scenarios would happen at the same time (from the perspective of the mathematical model), you would only have the `ROOT` scenario followed by a list of your scenarios. In that case, you could just provide the list of scenario names to the ScenarioModel instead a dict containing the tree. The `scenario_probabilities` dict assigns a probability to every scenario in the `scenario_tree`. The ScenarioModel validates that the probabilities of child scenarios sum up to the probability of their parent. ### Describing the effects of the scenarios We also need to describe how the scenarios change our `base_problem`. [ScenarioModel](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.scenario.ScenarioModel) handles this by having lists of constants, variables, objectives, constraints, extra functions, and scalarization functions, which are then assigned to scenarios as need be. It works like this, because it is often desirable to use, for example, same constraints in multiple different scenarios, and having them all be drawn from a single lists saves space is computer memory and database. We wanted to describe an electricity outage, so let's define constraints that say we cannot buy or sell electricity at specified times. We put one of these outages at the start of slices 2 and 3 of our timeseries variables. ``` from desdeo.problem import Constraint, ConstraintTypeEnum con_pool: list[Constraint] = [] con_idx: dict[str, int] = {} H = 4 # hours of grid outage for k in (2, 3): # start of timeseries slices 2 and 3 are the outage periods c = Constraint( name=f"Outage no-trade s{k} t=1..{H}", symbol=f"outage_trade_s{k}", func=["Add", ["Extract", f"buy_s{k}", ["Tuple", 1, H]], ["Extract", f"sell_s{k}", ["Tuple", 1, H]]], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_idx[c.symbol] = len(con_pool) con_pool.append(c) ``` The summer cabin is not primarily a business, so the real impact of the electricity outages is not really measured in how they affect the costs associated. What is more important, is having access to electricity at the cabin. ### Adding objectives To see, how for how many hours the cabin does not have enough electricity to meet the normal consumption, we are going to introduce a new objective function, that counts the hours when electricity demand is not met by either solar panels or battery storage. ``` from desdeo.problem import Objective def _f3(segments: tuple[int, ...]) -> Objective: z_terms = [["Sum", f"z_s{k}"] for k in segments] return Objective( name="Hours with unserved electricity demand", symbol="f_3", func=z_terms[0] if len(z_terms) == 1 else ["Add", *z_terms], unit="h", maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ) obj_pool: list[Objective] = [] obj_idx: dict[str, int] = {} # scenario name → pool index for scenario_name, segs in [("S2a", (2,)), ("S1b", (3,)), ("S2b", (2, 3))]: obj_idx[scenario_name] = len(obj_pool) obj_pool.append(_f3(segs)) obj_idx["S1a"] = len(obj_pool) obj_pool.append( Objective( name="Hours with unserved electricity demand", symbol="f_3", func=["Multiply", 0, "y"], # always 0 — no outage possible in this scenario unit="h", maximize=False, is_linear=True, is_convex=True, is_twice_differentiable=True, ) ) ``` The objective function has different values for all four scenarios. Of course, it would be possible in this problem to use the same objective function formulation for all scenarios, but that would require us to define the `z_sk` variables for all scenarios, and we do not really want to do that to keep the problem size smaller. ### Adding variables Of course, we also need to add the variables `z_sk` that appear in the objective functions. ``` from desdeo.problem import TensorVariable, Variable, VariableTypeEnum var_pool: list[Variable] = [] var_idx: dict[str, int] = {} for k in (2, 3): v = TensorVariable( name=f"Demand unserved indicator s{k}", symbol=f"z_s{k}", shape=[H], variable_type=VariableTypeEnum.binary, lowerbounds=0, upperbounds=1, initial_values=0, ) var_idx[v.symbol] = len(var_pool) var_pool.append(v) ``` To have variables `z_sk` to actually indicate whether there is enough electricity or not, we are also going to need additional variables and constraints that implement that logic. ``` _M_UNMET = 15.0 # kWh upper bound for big-M constraints (exceeds any single-hour load) for k in (2, 3): v = TensorVariable( name=f"Unmet demand s{k} (kWh)", symbol=f"unmet_s{k}", shape=[H], variable_type=VariableTypeEnum.real, lowerbounds=0.0, upperbounds=None, initial_values=0.0, ) var_idx[v.symbol] = len(var_pool) var_pool.append(v) for k in (2, 3): c = Constraint( name=f"Energy balance s{k} t=1..{H} (with unmet slack)", symbol=f"energy_bal_out_s{k}", func=[ "Add", ["Extract", f"d_s{k}", ["Tuple", 1, H]], # discharging from battery ["Negate", ["Extract", f"c_s{k}", ["Tuple", 1, H]]], # charging battery ["Multiply", "n", ["Extract", f"sol_s{k}", ["Tuple", 1, H]]], # solar generation f"unmet_s{k}", # unmet demand ["Negate", ["Extract", f"l_s{k}", ["Tuple", 1, H]]], # load ], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_idx[c.symbol] = len(con_pool) con_pool.append(c) for k in (2, 3): c = Constraint( name=f"Big-M unmet indicator s{k} t=1..{H}", symbol=f"bigm_s{k}", func=["Subtract", f"unmet_s{k}", ["Multiply", _M_UNMET, f"z_s{k}"]], cons_type=ConstraintTypeEnum.LTE, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_idx[c.symbol] = len(con_pool) con_pool.append(c) ``` ### Changing constraints We also need to update the energy balance constraint for the scenarios where we have an outage. It does not include the unmet demand component and would lead to model infeasibility when electricity cannot be bought or sold and the battery and solar are not enough. By using a same symbol that already exist in the base_problem for the Constraint (or any other Problem component), we are overwriting that constraint in the base problem. This only affects the scenarios that we include the constraint in. ``` for k in (2, 3): c = Constraint( name=f"Energy balance s{k} t={H}+1.. (no unmet slack)", symbol=f"energy_bal_s{k}", func=[ "Add", ["Exclude", f"buy_s{k}", ["Tuple", 1, H]], ["Negate", ["Exclude", f"sell_s{k}", ["Tuple", 1, H]]], ["Exclude", f"d_s{k}", ["Tuple", 1, H]], ["Negate", ["Exclude", f"c_s{k}", ["Tuple", 1, H]]], ["Multiply", "n", ["Exclude", f"sol_s{k}", ["Tuple", 1, H]]], ["Negate", ["Exclude", f"l_s{k}", ["Tuple", 1, H]]], ], cons_type=ConstraintTypeEnum.EQ, is_linear=True, is_convex=True, is_twice_differentiable=True, ) con_idx[c.symbol] = len(con_pool) con_pool.append(c) ``` ### Constructing the scenarios Now we are ready to construct the [Scenario](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.scenario.ScenarioModel) objects that describe which Variables, Constraints, and Objectives should be used in which scenario. ``` from desdeo.problem import Scenario # Dict mapping scenario names to the segments that are outaged in that scenario _outage_segs: dict[str, tuple[int, ...]] = {"S1a": (), "S2a": (2,), "S1b": (3,), "S2b": (2, 3)} scenarios: dict[str, Scenario] = {} for name, segs in _outage_segs.items(): variables: dict[str, int] = {} constraints: dict[str, int] = {} for k in segs: variables[f"unmet_s{k}"] = var_idx[f"unmet_s{k}"] variables[f"z_s{k}"] = var_idx[f"z_s{k}"] constraints[f"energy_bal_s{k}"] = con_idx[f"energy_bal_s{k}"] constraints[f"energy_bal_out_s{k}"] = con_idx[f"energy_bal_out_s{k}"] constraints[f"bigm_s{k}"] = con_idx[f"bigm_s{k}"] constraints[f"outage_trade_s{k}"] = con_idx[f"outage_trade_s{k}"] scenarios[name] = Scenario( variables=variables, objectives={"f_3": obj_idx[name]}, constraints=constraints, ) ``` ### Defining anticipation stop The last thing we need to define in our [ScenarioModel](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.scenario.ScenarioModel) is anticipation stop. It describes which scenarios are allowed to affect values of the listed Variables. The scenario under which the Variable is listed is the last scenario that can affect the value of the Variable. Thus, Variables listed under `"ROOT"` must have the same values in all scenarios. Variables listed under `"S2"` must have the same value in all scenarios that follow `"S2"`, and so on. In this summer cabin electricity problem, the decisions associated with time before the first possible electricity outage must all have the same values in all scenarios. The decision variables that follow the first potential outage can have their values depend on whether that outage happened, but they cannot depend on the second outage happening. ``` investments = ["y", "E", "n"] s1_sched = ["c_s1", "d_s1", "soc_s1", "buy_s1", "sell_s1"] s2_sched = ["c_s2", "d_s2", "soc_s2", "buy_s2", "sell_s2"] s2_unmet = ["unmet_s2", "z_s2"] anticipation_stop = { "ROOT": [*investments, *s1_sched], "S1": s2_sched, # no unmet demand variables since no outage in S1 "S2": [*s2_sched, *s2_unmet], } ``` ### Ready scenario model Now we just put the scenario model together. ``` from desdeo.problem.scenario import ScenarioModel summer_cabin_scenarios = ScenarioModel( scenario_tree=scenario_tree, scenario_probabilities=scenario_probabilities, base_problem=base, variables=tuple(var_pool), objectives=tuple(obj_pool), constraints=tuple(con_pool), scenarios=scenarios, anticipation_stop=anticipation_stop, ) ``` # Using scenario models Currently, there are two ways of using scenario models within DESDEO: constructing Problems corresponding to individual scenarios and building aggregate problems consisting of multiple scenarios. You can construct individual scenario problems by calling the `get_scenario_problem` function. This is unlikely to be that useful on its own, but can be useful for sanity checks or for constructing more complex methods. ``` from desdeo.tools import guess_best_solver scenario_2b = summer_cabin_scenarios.get_scenario_problem("S2b") results = guess_best_solver(scenario_2b)(scenario_2b).solve("f_1") pprint(results.optimal_objectives) ``` ``` {'f_1': -170.38648708994592, 'f_2': 25020.0, 'f_3': 8.0} ``` Likely a more useful way to utilize scenario models is by using one of the implemented aggregation methods that combine multiple scenarios into a single multiobjective optimization problem. ``` import inspect import desdeo.tools.stochastic as mod for name, obj in inspect.getmembers(mod, inspect.isfunction): if obj.__module__ == mod.__name__: pprint(f"{name}") import desdeo.tools.robust as mod for name, obj in inspect.getmembers(mod, inspect.isfunction): if obj.__module__ == mod.__name__: pprint(f"{name}") del mod ``` ``` 'add_conditional_value_at_risk' 'add_expected_asf' 'add_expected_value' 'add_weighted_scenarios' 'add_worst_case_robust' ``` The way these aggregation functions work is they construct one big scenario model using [build_combined_scenario_problem](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.scenarios.build_combined_scenario_problem) and then add aggregation functions that combine the values from multiple scenarios into a single function expression. Let us look at the [add_expected_value](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.stochastic.add_expected_value) as an example. ``` from desdeo.tools import add_expected_value # We want to compute the expected value of all three objectives across the scenarios combined_ev_problem, new_symbols = add_expected_value( scenario_model=summer_cabin_scenarios, symbols=["f_1", "f_2", "f_3"]) pprint([o.name for o in combined_ev_problem.objectives]) ``` ``` ['Hours with unserved electricity demand (S1a_f_3)', 'Hours with unserved electricity demand (S2b_f_3)', 'Hours with unserved electricity demand (S1b_f_3)', 'Hours with unserved electricity demand (S2a_f_3)', 'Electricity cost (S1a_f_1)', 'Electricity cost (S2b_f_1)', 'Electricity cost (S1b_f_1)', 'Electricity cost (S2a_f_1)', 'Investment cost (f_2)', 'Expected value of f_1', 'Expected value of f_2', 'Expected value of f_3'] ``` As we can see, our `combined_ev_problem` has a total of 12 objectives including the expected values of the three original objective functions. It is unlikely anyone is going to care about all these 12 objectives that much, especially considering how similar they are. Thus, to find a solution that a decision maker might be interested in, we are using partial scalarization, that only uses a subset of the objectives. ``` from desdeo.tools import CVXPYSolver, add_asf_partial_diff, payoff_table_method # Calculate ideal and nadir values, so that the ASF can be properly scaled ideal, nadir = payoff_table_method(combined_ev_problem, CVXPYSolver) combined_ev_problem = combined_ev_problem.update_ideal_and_nadir(ideal, nadir) pprint(ideal) pprint(nadir) ``` ``` {'E_f_1': -170.2034948424482, 'E_f_2': 0.0, 'E_f_3': 0.0, 'S1a_f_1': -170.2157368877032, 'S1a_f_3': 0.0, 'S1b_f_1': -171.05123923339914, 'S1b_f_3': 0.0, 'S2a_f_1': -169.55098474424992, 'S2a_f_3': 0.0, 'S2b_f_1': -170.38648708994592, 'S2b_f_3': 0.0, 'f_2': 0.0} {'E_f_1': 284.1993394723681, 'E_f_2': 25020.0, 'E_f_3': 0.7999999999999998, 'S1a_f_1': 284.3543099288125, 'S1a_f_3': 0.0, 'S1b_f_1': 283.8928728809143, 'S1b_f_3': 4.0, 'S2a_f_1': 283.17025631593975, 'S2a_f_3': 4.0, 'S2b_f_1': 287.78745536436577, 'S2b_f_3': 8.0, 'f_2': 25020.0} ``` ``` reference_point = {'E_f_1': 0, 'E_f_2': 5000.0, 'E_f_3': 0} asf_problem, symbol = add_asf_partial_diff(combined_ev_problem, symbol="ASF", reference_point=reference_point) solver = CVXPYSolver(asf_problem) results = solver.solve(symbol) pprint(results.optimal_objectives) ``` ``` {'E_f_1': 83.92565751178836, 'E_f_2': 9621.053814752766, 'E_f_3': 0.09999999999999999, 'S1a_f_1': 83.86840202796994, 'S1a_f_3': 0.0, 'S1b_f_1': 83.37371196251193, 'S1b_f_3': 1.0, 'S2a_f_1': 84.65288793569992, 'S2a_f_3': 0.0, 'S2b_f_1': 86.98578782937489, 'S2b_f_3': 1.0, 'f_2': 9621.053814752766} ``` ### Adding multiple aggregation functions It is also possible add multiple scenario aggregation functions into the same problem. If you want to do that, you need to handle the combined scenario manually, because otherwise the aggregation functions have no way to figure out what is part of the original base problem and what was added later. In the example below we add worst case robust aggregation and expected value aggregation into the summer cabin problem. ``` from desdeo.tools import add_worst_case_robust, build_combined_scenario_problem combined_problem, symbol_maps = build_combined_scenario_problem(summer_cabin_scenarios) combined_problem, added = add_worst_case_robust( scenario_model=summer_cabin_scenarios, symbols=["f_1", "f_2", "f_3"], combined=combined_problem, symbol_maps=symbol_maps, ) combined_problem, added2 = add_expected_value( scenario_model=summer_cabin_scenarios, symbols=["f_1", "f_2", "f_3"], combined=combined_problem, symbol_maps=symbol_maps, ) # Calculate ideal and nadir values, so that the ASF can be properly scaled ideal, nadir = payoff_table_method(combined_problem, CVXPYSolver) combined_problem = combined_problem.update_ideal_and_nadir(ideal, nadir) pprint(ideal) pprint(nadir) ``` ``` {'E_f_1': -170.20349484244818, 'E_f_2': 0.0, 'E_f_3': 0.0, 'S1a_f_1': -170.2157368877032, 'S1a_f_3': 0.0, 'S1b_f_1': -171.05123923339914, 'S1b_f_3': 0.0, 'S2a_f_1': -169.55098474424992, 'S2a_f_3': 0.0, 'S2b_f_1': -170.38648708994592, 'S2b_f_3': 0.0, 'f_2': 0.0, 'robust_f_1': -169.42350644620245, 'robust_f_2': 0.0, 'robust_f_3': 0.0} {'E_f_1': 285.57658537379876, 'E_f_2': 25020.0, 'E_f_3': 0.7999999999999998, 'S1a_f_1': 285.46864783024233, 'S1a_f_3': 0.0, 'S1b_f_1': 286.0099468786688, 'S1b_f_3': 4.0, 'S2a_f_1': 285.74519421736943, 'S2a_f_3': 4.0, 'S2b_f_1': 288.9017932657958, 'S2b_f_3': 8.0, 'f_2': 25020.0, 'robust_f_1': 289.0, 'robust_f_2': 25020.0, 'robust_f_3': 8.0} ``` As seen above, the number of objective functions is quite large now. We can once again solve the problem using partial scalarization. Let's say we care about the expected value for the electricity costs, the cost of investments, and the maximum value of hours without electricity. ``` reference_point = {'E_f_1': 0, 'f_2': 5000.0, 'robust_f_3': 0} asf_problem, symbol = add_asf_partial_diff(combined_problem, symbol="ASF", reference_point=reference_point) solver = CVXPYSolver(asf_problem) results = solver.solve(symbol) pprint(results.optimal_objectives) ``` ``` {'E_f_1': 83.96907117794157, 'E_f_2': 9609.47341067498, 'E_f_3': 0.09999999999999999, 'S1a_f_1': 83.97957085314236, 'S1a_f_3': 0.0, 'S1b_f_1': 83.38759433961908, 'S1b_f_3': 1.0, 'S2a_f_1': 84.46655061465756, 'S2a_f_3': 0.0, 'S2b_f_1': 83.87457410113473, 'S2b_f_3': 1.0, 'f_2': 9609.473410674978, 'robust_f_1': 84.46655061465756, 'robust_f_2': 9609.473410674978, 'robust_f_3': 1.0} ``` # Crossover operators in DESDEO[¶](#crossover-operators-in-desdeo) Crossover is the step in an evolutionary algorithm that turns (usually) two *parent* solutions into one or more *offsprings*. It is the main source of exploration in an EA. Mutation nudges a single solution and introduces small changes, crossover recombines information that two different solutions have discovered. DESDEO implements nine crossover operators. They all expose the same interface, so swapping one for another is a one-line change, as long as the problem is compatible with the operator. Each operator currently is designed to handle, e.g., either a problem with all continuous variables, all binary variables, all integer variables or mixed integer/continuous variables. This page is about what these operators do, shown through the distribution of the offspring they generate based on specific parent populations. The implementation details of these operators are presented at the end of this page. Related reading: - [Evolutionary Algorithms in DESDEO](https://desdeo.readthedocs.io/en/latest/explanation/templates_and_pub_sub) — how operators are assembled into an algorithm. - [Pydantic interface](https://desdeo.readthedocs.io/en/latest/explanation/pydantic_interface) and [Using evolutionary algorithms](https://desdeo.readthedocs.io/en/latest/howtoguides/ea_options) — how to configure an operator without writing code. ## Comparison at a glance[¶](#comparison-at-a-glance) | Operator | Variable type | Parameters | Where the offspring land | How the bounds are respected | | -------------------------------- | ------------- | --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `SimulatedBinaryCrossover` | continuous | `xover_distribution` (η), `xover_probability`, `uniform_xover_probability`, `truncated` | close to **both** parents; polynomial density in a spread factor β | the sampling distribution is truncated at the bounds, or the offspring are clipped onto them if `truncated=False` | | `BlendAlphaCrossover` | continuous | `alpha`, `repeats`, `sample_each_component` | uniformly over the parent interval, widened by α | sampling interval is intersected with the bounds | | `LocalCrossover` | continuous | — | uniformly **between** the parents, fresh weight per variable | cannot leave the parent segment | | `SingleArithmeticCrossover` | continuous | `xover_probability` | one gene set to the parent mean, every other gene copied | cannot leave the parent segment | | `BoundedExponentialCrossover` | continuous | `lambda_` (λ), `xover_probability`, `uniform_xover_probability` | around **its own** parent, exponential decay | the sampling distribution is truncated at the bounds | | `DifferentialEvolutionCrossover` | continuous | `scaling_factor` (F), `xover_probability` (CR) | on **its own** target, displaced by the difference of two other population members | offspring are clipped onto the bounds | | `ParentCentricCrossover` | continuous | `sigma_zeta`, `sigma_eta` | around **one** of three parents, along and across the direction to their centroid | offspring are clipped onto the bounds | | `UniformCrossover` | continuous | `uniform_xover_probability`, `pair_xover_probability` | **on** the parents; each gene independently taken from one or the other, never blended | cannot leave the parents' values, so the bounds are respected by construction | | `SinglePointBinaryCrossover` | binary | — | contiguous blocks swapped at one cut point | n/a | | `UniformIntegerCrossover` | integer | — | each gene independently taken from either parent | n/a | | `UniformMixedIntegerCrossover` | mixed | — | as above, without rounding the continuous genes | n/a | | `CompositeCrossover` | inherited | `operators` | delegates to sub-operators in round-robin | inherited | ### Behaviour of operators for continuous variables[¶](#behaviour-of-operators-for-continuous-variables) Both parents below have every variable at $3.0$ and $7.0$ respectively, on the box $[0, 10]^2$. Each panel shows the distribution of 80000 offspring of the first variable, drawn from that same pair of parents over and over. Some remarks on the distributions: - **Simulated binary**, at its default $\\eta = 30$, is the most concentrated operator on the page. Every offspring lands within $[2.06, 7.94]$ and *all* of them fall within $0.5$ of a parent. This behaviour is remarked upon in literature and is intended. - **Bounded exponential**, at its default $\\lambda = 0.1$, looks much the same: 72% of its offspring land within $0.5$ of a parent, and almost none in the middle. It differs in having thin tails that do reach the rest of the range. - **Blend alpha** and **local** fill an interval uniformly instead. Local never leaves $[3, 7]$; blend alpha spills out to $[1, 9]$, a margin set by default $\\alpha = 0.5$. - **Uniform** is the degenerate case: two spikes, one on each parent, and nothing anywhere else. It is the only operator here that creates no new values, which is what makes it the reference point for what recombination contributes without interpolation. - **Single arithmetic** produces three spikes, and the middle one holds half the mass. With two variables it modifies $x_1$ only half the time: those offspring land exactly on the parent mean, and the rest keep their own parent's $x_1$ untouched, a quarter on each parent. Two operators are missing from that figure, and unavoidably so: **differential evolution** and **parent-centric crossover** recombine more than two parents, so a fixed pair does not define their behaviour. They get their own section below. The operators fall into two categories: those that pile offspring *onto* the parents versus operators that fill the space *between* them. The rest of this page takes each operator in turn, starting with the two parent-centric ones. ## Simulated binary crossover (SBX)[¶](#simulated-binary-crossover-sbx) SBX is the default for every continuous algorithm in DESDEO. It was designed to reproduce, for real-valued variables, the *effect* single-point crossover has on binary strings: offspring that mostly resemble one parent or the other, with the occasional distant explorer. It draws a **spread factor** $\\beta$ from a polynomial distribution controlled by the distribution index $\\eta$: $$ P(\\beta) ;\\propto; \\begin{cases} \\beta^{\\eta} & \\beta \\le 1 \\quad \\text{(contracting)}\\[4pt] \\beta^{-(\\eta+2)} & \\beta > 1 \\quad \\text{(expanding)} \\end{cases} $$ Sampling it by inverting the CDF against a uniform $\\mu$ gives us: $$ \\beta = \\begin{cases} (2\\mu)^{\\frac{1}{\\eta+1}} & \\mu \\le 0.5\\[4pt] \\bigl(2 - 2\\mu\\bigr)^{-\\frac{1}{\\eta+1}} & \\mu > 0.5 \\end{cases} \\qquad c\_{1,2} = \\bar{x} \\mp \\beta,\\frac{x_1 - x_2}{2} $$ where $\\bar{x}$ is the parent mean. The density of $\\beta$ peaks at $\\beta = 1$, and $\\beta = 1$ means "land on a parent". Note what the second equation says: SBX is built around the **parent mean**, and the sign in front of $\\beta$ decides which parent a given child is pulled toward. That sign is a coin flip, and it is a knob — see [per-variable mixing](#per-variable-mixing-the-uniform-crossover-layer) below. References: Deb & Agrawal (1995), *Simulated binary crossover for continuous search space*, Complex Systems 9(2); Deb & Gulati (2001), *Design of truss-structures for minimum weight using genetic algorithms*, Finite Elements in Analysis and Design 37(5). In \[3\]: Copied! ``` # Built with its defaults: xover_distribution=30, xover_probability=1.0, # uniform_xover_probability=0.5, truncated=True. sbx = SimulatedBinaryCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) ``` # Built with its defaults: xover_distribution=30, xover_probability=1.0, # uniform_xover_probability=0.5, truncated=True. sbx = SimulatedBinaryCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) ### η controls how far offspring stray[¶](#controls-how-far-offspring-stray) $\\eta$ is the only parameter that changes the *shape* of the distribution, and it changes it drastically. The tail of $P(\\beta)$ is a power law, so it is heavy: at $\\eta = 2$ the sampled offspring of parents at $3$ and $7$ routinely fall outside $[0, 10]$ and are pulled back onto the bounds, leaving 3.2% of them sitting exactly on a bound. By $\\eta = 15$ nothing reaches a bound at all, and at the default $\\eta = 30$ the whole distribution has collapsed very close to the two parents. ### `truncated`: whether the sampling distribution itself is truncated[¶](#truncated-whether-the-sampling-distribution-itself-is-truncated) Both variants return offspring inside the feasible box — that is no longer the difference between them. What differs is *how* they get there. - **`truncated=True`** (the default) uses the truncated formulation of Deb & Gulati, which rescales $\\beta$ per variable so the offspring is **generated** inside the bounds in the first place. Nothing has to be clipped. - **`truncated=False`** samples $\\beta$ from the untruncated polynomial density above, computes the offspring, and then **clips** whatever fell outside back onto the nearest bound. Clipping takes all the probability mass that fell outside and stacks it onto a single value, producing a **point mass sitting exactly on the bound**. Truncation instead redistributes that mass smoothly across the interior, so no single value is special. Most other frameworks — pymoo, jMetalPy, Platypus, pagmo2, and Deb's NSGA-II C code — implement the truncated variant while simply calling it "SBX". PlatEMO on the other hand implements the untruncated variant, also calling it "SBX". DESDEO gives you both and defaults to the truncated one, so it agrees with the majority out of the box; set `truncated=False` if you want PlatEMO's behaviour. How much it matters depends on how much mass the untruncated density puts outside the box, which in turn depends on **how close the parents sit to a bound** and on $\\eta$. The panels below sweep the parents from hard against the lower bound to the middle of the range. They use $\\eta = 5$ rather than the default $\\eta = 30$, because at the default the distribution is so tight that neither variant ever reaches a bound and the two are indistinguishable unless one or both of the parents are at a bound. This behaviour can have a significant effect on the search, especially in problems where the optimum sits on a bound. ## Bounded exponential crossover (BEX)[¶](#bounded-exponential-crossover-bex) BEX is **parent-centric** in the strictest sense: each offspring is a displacement away from *its own* parent, not from the parent mean. That holds at the default `uniform_xover_probability = 0.0`. Raising it lets the two offspring exchange, per variable, which parent they descend from — the same uniform-crossover component `SimulatedBinaryCrossover` carries under that name. At `0.5` roughly half of each offspring's variables come from the other parent's line, which trades the strict parent-centricity above for mixing between the two lines. $$ c = x + \\beta,|x_1 - x_2| $$ where $\\beta$ comes from inverting the CDF of an exponential distribution that has been **truncated at the variable bounds** — one branch toward the lower bound, one toward the upper, chosen by a coin flip: $$ \\beta = \\begin{cases} \\lambda \\log!\\bigl(e\_{\\text{lo}} + u,(1 - e\_{\\text{lo}})\\bigr), & r \\le 0.5\\[4pt] -\\lambda \\log!\\bigl(1 - u,(1 - e\_{\\text{hi}})\\bigr), & r > 0.5 \\end{cases} \\qquad \\begin{aligned} e\_{\\text{lo}} &= \\exp!\\Bigl(\\tfrac{x^{\\text{lo}} - x}{\\lambda,|x_1 - x_2|}\\Bigr)\\ e\_{\\text{hi}} &= \\exp!\\Bigl(\\tfrac{x - x^{\\text{up}}}{\\lambda,|x_1 - x_2|}\\Bigr) \\end{aligned} $$ Because the truncation is built into the sampling, the offspring are inside the bounds by construction. λ scales the exponential relative to the distance between the parents. It changes the spread only: the median offspring sits on its own parent for every λ — again with `uniform_xover_probability` at its default, since exchanging a variable moves that offspring's median onto the *other* parent. References: Thakur, Meghwani & Jalota (2014), *A modified real coded genetic algorithm for constrained optimization*, Applied Mathematics and Computation 235; modifying the Laplace crossover of Deep & Thakur (2007). In \[6\]: Copied! ``` # Built with its defaults: lambda_=0.1, xover_probability=1.0. bex = BoundedExponentialCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) ``` # Built with its defaults: lambda\_=0.1, xover_probability=1.0. bex = BoundedExponentialCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) Every curve peaks on the parents and decays away from them; λ changes only how fast. At $\\lambda = 0.01$ the operator is barely doing anything — every offspring is within $0.5$ of a parent. The default $\\lambda = 0.1$ loosens that to 72%, and by $\\lambda = 0.5$ only 29% are still near a parent and the distribution is flattening toward uniform. What λ never does is move the peaks: the median offspring sits on its own parent at every setting. Contrast SBX, where η reshapes a *polynomial* density built around the parent mean, and where offspring essentially never land at the midpoint at all. ### SBX and BEX at their defaults[¶](#sbx-and-bex-at-their-defaults) The two operators share a family resemblance — both put their offspring on the parents rather than between them — but their *default* settings are worlds apart in how far they let the offspring wander. At their defaults the SBX operator is much more concentrated than BEX. However, the general behaviour of the two operators is similar: both have a peak on the parents and a tail that decays away from them. ## Blend alpha crossover (BLX-α)[¶](#blend-alpha-crossover-blx-) BLX-α takes the interval spanned by the two parents, widens it by a fraction α of its own length at both ends, and samples uniformly from the range: $$ c \\sim U\\bigl[,c\_{\\min} - \\alpha d,; c\_{\\max} + \\alpha d,\\bigr], \\qquad d = |x_1 - x_2|. $$ If the bound of the above interval exceeds the variable bounds, it is clipped to the closest bound before sampling. At $\\alpha = 0$ offspring are confined strictly between the parents; larger α lets them explore outside. BLX-α is also the one operator that can produce any number offspring per pair, via the `repeats` argument, which repeatedly samples from the interval. Reference: Eshelman & Schaffer (1993), *Real-coded genetic algorithms and interval-schemata*, FOGA 2. In \[9\]: Copied! ``` # Built with its defaults: alpha=0.5, repeats=2, sample_each_component=True. blx = BlendAlphaCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) ``` # Built with its defaults: alpha=0.5, repeats=2, sample_each_component=True. blx = BlendAlphaCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) Each α gives a flat-topped uniform distribution whose width grows with α. At $\\alpha = 0$ the interval is exactly $[3, 7]$. ## Uniform crossover[¶](#uniform-crossover) `UniformCrossover` inherits every variable whole from one parent or the other, with the two offspring taking complementary choices. Nothing is interpolated, so the offspring's genes are exactly the parents' genes and the operator can only rearrange the material already in the population. The real-coded literature calls this *discrete* crossover. In \[11\]: Copied! ``` rates = [0.0, 0.25, 0.5, 0.75, 1.0] symbols = [v.symbol for v in PROBLEM.get_flattened_variables()] print(f"{'u':>6} {'gene equals a parent':>21} {'taken from the other parent':>28}") for rate in rates: operator = UniformCrossover( problem=PROBLEM, publisher=Publisher(), verbosity=2, seed=0, uniform_xover_probability=rate ) n_pairs = 20000 population = pl.DataFrame(np.tile(np.array([PARENT_A, PARENT_B], dtype=float), (n_pairs, 1)), schema=symbols) children = operator.do(population=population, to_mate=list(range(2 * n_pairs))).to_numpy()[:n_pairs] parents = operator.parent_population[symbols].to_numpy() from_first = np.isclose(children, parents[0::2]) from_second = np.isclose(children, parents[1::2]) inherited = (from_first | from_second).mean() swapped = (from_second & ~from_first).mean() print(f"{rate:>6.2f} {inherited:>21.3f} {swapped:>28.3f}") ``` rates = [0.0, 0.25, 0.5, 0.75, 1.0] symbols = [v.symbol for v in PROBLEM.get_flattened_variables()] print(f"{'u':>6} {'gene equals a parent':>21} {'taken from the other parent':>28}") for rate in rates: operator = UniformCrossover( problem=PROBLEM, publisher=Publisher(), verbosity=2, seed=0, uniform_xover_probability=rate ) n_pairs = 20000 population = pl.DataFrame(np.tile(np.array([PARENT_A, PARENT_B], dtype=float), (n_pairs, 1)), schema=symbols) children = operator.do(population=population, to_mate=list(range(2 * n_pairs))).to_numpy()[:n_pairs] parents = operator.parent_population[symbols].to_numpy() from_first = np.isclose(children, parents[0::2]) from_second = np.isclose(children, parents[1::2]) inherited = (from_first | from_second).mean() swapped = (from_second & ~from_first).mean() print(f"{rate:>6.2f} {inherited:>21.3f} {swapped:>28.3f}") ``` u gene equals a parent taken from the other parent 0.00 1.000 0.000 0.25 1.000 0.247 0.50 1.000 0.498 0.75 1.000 0.750 1.00 1.000 1.000 ``` ## Local crossover[¶](#local-crossover) Local crossover is the plain arithmetic recombination: a random convex combination of the two parents, with a fresh weight drawn for every decision variable. $$ c_1 = \\alpha x_1 + (1 - \\alpha) x_2, \\qquad c_2 = (1 - \\alpha) x_1 + \\alpha x_2, \\qquad \\alpha \\sim U[0, 1] $$ Because α is a convex weight, offspring can never leave the segment between the parents. It takes no parameters at all. Reference: Dumitrescu, Lazzerini, Jain & Dumitrescu (2000), *Evolutionary Computation*, CRC Press. In \[12\]: Copied! ``` local = LocalCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) ``` local = LocalCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) ## Single arithmetic crossover[¶](#single-arithmetic-crossover) The most conservative operator here. It picks **one** variable position $k$ at random and replaces it, in both offspring, with the mean of the parents at that position. Every other variable is copied unchanged: $$ c\_{1,k} = c\_{2,k} = \\frac{x\_{1,k} + x\_{2,k}}{2}, \\qquad c\_{i,j} = x\_{i,j} ;; \\text{for } j \\neq k $$ `xover_probability` is the chance that a given *pair* is recombined at all; pairs that fail the roll are passed through untouched. Note that $k$ is drawn per pair, so on a two-variable problem $x_1$ is the chosen position only half the time. That is what produces the three spikes in the overview figure: about half the offspring sit on the parent mean, and the remaining half keep their own parent's $x_1$ exactly, split evenly between the two parents. Reference: Picek, Jakobovic & Golub (2013), CEC. In \[13\]: Copied! ``` # Built with its default: xover_probability=1.0. single_arithmetic = SingleArithmeticCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) ``` # Built with its default: xover_probability=1.0. single_arithmetic = SingleArithmeticCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0) ## Operators that use more than two parents[¶](#operators-that-use-more-than-two-parents) Every operator above is a function of a parent *pair*. Two are not. **Differential evolution** (`DE/rand/1/bin`) builds each offspring from its target and three other population members: it forms $v = x\_{r_1} + F(x\_{r_2} - x\_{r_3})$ and then copies components of $v$ onto the target with probability `xover_probability`, always taking at least one so that no offspring is a copy of its target. **Parent-centric crossover** draws three parents, designates one of them the *index* parent, and places the offspring beside it — displaced along the direction from the parental centroid to the index parent, and across that direction by an amount set by how far the other two parents sit from it. The practical consequence is the same for both: the step size is set by the population rather than by the mating pair. A solution far from the rest of the population is displaced no further than one inside a tight cluster, which is not true of any pairwise operator. In \[14\]: Copied! ``` # These operators need a population rather than a fixed pair, so the panels below show one # population (open circles) together with the offspring it produces. SBX is included for reference. rng = np.random.default_rng(0) symbols = [v.symbol for v in PROBLEM.get_flattened_variables()] members = np.clip(rng.normal([4.0, 6.0], 1.2, size=(60, 2)), 0.2, 9.8) population = pl.DataFrame(members, schema=symbols) multi_parent = [ ("Simulated binary", SimulatedBinaryCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0)), ( "Differential evolution", DifferentialEvolutionCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0), ), ("Parent centric", ParentCentricCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0)), ] fig = make_subplots( rows=1, cols=3, shared_xaxes=True, shared_yaxes=True, horizontal_spacing=0.05, subplot_titles=[name for name, _ in multi_parent], ) for column, ((_name, operator), colour) in enumerate(zip(multi_parent, IDENTITY, strict=False), start=1): offspring = np.vstack([operator.do(population=population).to_numpy() for _ in range(40)]) fig.add_trace( go.Scatter( x=offspring[:, 0], y=offspring[:, 1], mode="markers", showlegend=False, marker={"size": 3, "color": colour, "opacity": 0.3}, ), row=1, col=column, ) fig.add_trace( go.Scatter( x=members[:, 0], y=members[:, 1], mode="markers", showlegend=False, marker={"size": 6, "color": INK, "symbol": "circle-open"}, ), row=1, col=column, ) style(fig, "Offspring of one 60-member population (○), 2400 draws per operator", "", "", height=400, showlegend=False) fig.update_xaxes(title_text="x₁", range=[0, 10]) fig.update_yaxes(title_text="x₂", range=[0, 10]) show(fig) ``` # These operators need a population rather than a fixed pair, so the panels below show one # population (open circles) together with the offspring it produces. SBX is included for reference. rng = np.random.default_rng(0) symbols = [v.symbol for v in PROBLEM.get_flattened_variables()] members = np.clip(rng.normal([4.0, 6.0], 1.2, size=(60, 2)), 0.2, 9.8) population = pl.DataFrame(members, schema=symbols) multi_parent = [ ("Simulated binary", SimulatedBinaryCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0)), ( "Differential evolution", DifferentialEvolutionCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0), ), ("Parent centric", ParentCentricCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0)), ] fig = make_subplots( rows=1, cols=3, shared_xaxes=True, shared_yaxes=True, horizontal_spacing=0.05, subplot_titles=[name for name, _ in multi_parent], ) for column, ((\_name, operator), colour) in enumerate(zip(multi_parent, IDENTITY, strict=False), start=1): offspring = np.vstack([operator.do(population=population).to_numpy() for _ in range(40)]) fig.add_trace( go.Scatter( x=offspring[:, 0], y=offspring[:, 1], mode="markers", showlegend=False, marker={"size": 3, "color": colour, "opacity": 0.3}, ), row=1, col=column, ) fig.add_trace( go.Scatter( x=members[:, 0], y=members[:, 1], mode="markers", showlegend=False, marker={"size": 6, "color": INK, "symbol": "circle-open"}, ), row=1, col=column, ) style(fig, "Offspring of one 60-member population (○), 2400 draws per operator", "", "", height=400, showlegend=False) fig.update_xaxes(title_text="x₁", range=[0, 10]) fig.update_yaxes(title_text="x₂", range=[0, 10]) show(fig) ## Per-variable mixing[¶](#per-variable-mixing) Several continuous operators carry a second, separate mechanism inside them: a per-variable choice that is applied on top of the sampling equations above. It shows up in these operators: - **SBX** can swap individual variables between offsprings after the SBX operation, controlled by `uniform_xover_probability`. - **BLX-α** has the`sample_each_component` argument: one random weight per variable, or a single weight reused across the whole offspring vector. - **`UniformCrossover`** is this mechanism on its own, with no sampling equation underneath it. Its `uniform_xover_probability` means exactly what SBX's does, so the two can be set to the same value and compared. To see this at all, the offspring have to be split by **which parent they descend from** — pooled together, the two streams cancel out and the marginal looks symmetric no matter what this parameter is set to. At $u = 0$ each child stays on its own parent. At $u = 1$ the roles are swapped wholesale, and every child takes after the other parent. At $u = 0.5$, the default, the two streams overlap exactly, and it is only their sum that looks like the familiar symmetric SBX picture. Many operators also have the `xover_probability` argument: how many genes get recombined at all. It is a per-variable gate applied *before* the mixing above: genes that fail the roll are copied from the parent untouched. ### `sample_each_component` in BLX-α[¶](#sample_each_component-in-blx-) Another way in which the distrubution of operators can be changed is whether a single random weight is used for all variables, or a fresh weight is drawn for each variable. This can be controlled in BLX-α by the `sample_each_component` argument. ## Operators for discrete variables[¶](#operators-for-discrete-variables) Three operators handle non-continuous variables. They share the same skeleton and differ only in *how the genes are divided* between the parents, and in how the values are cast. - **`SinglePointBinaryCrossover`** — binary variables. One cut point is drawn per pair, and the two parents swap everything after it. Because the cut is a single position, neighbouring genes tend to be inherited together. - **`UniformIntegerCrossover`** — integer variables. Every gene is independently taken from one parent or the other, using a mask drawn fresh for each pair. - **`UniformMixedIntegerCrossover`** — identical to the above, but for mixed-integer algorithms. None of the three takes any parameters. In \[18\]: Copied! ``` binary_problem = demo_problem(10, "binary", 0, 1) single_point = SinglePointBinaryCrossover(problem=binary_problem, publisher=Publisher(), verbosity=1, seed=0) ``` binary_problem = demo_problem(10, "binary", 0, 1) single_point = SinglePointBinaryCrossover(problem=binary_problem, publisher=Publisher(), verbosity=1, seed=0) Mating an all-zeros parent with an all-ones parent makes the inheritance pattern directly readable: for each gene position, the average offspring value *is* the probability that the gene came from the all-ones parent. Uniform crossover is flat at $0.5$, i.e., every gene is an independent coin flip, so position carries no information. Single-point crossover ramps from $0$ to $1$ across the binary string: the first gene almost always comes from the first parent and the last almost always from the second, because a single cut point cannot separate the ends. That ramp is also why single-point crossover preserves contiguous blocks of genes, and uniform crossover deliberately destroys them. ## Composite crossover[¶](#composite-crossover) `CompositeCrossover` wraps a list of operators and delegates to them in **round-robin**: the first call uses the first operator, the second call the second, and so on. It does **not** apply different operators to different variable groups — every wrapped operator receives the whole decision vector. All of them therefore have to suit the same kind of problem; you cannot pair a binary operator with a continuous one here. What it gives you is a way to alternate between several recombination behaviours over successive calls, for instance mixing a parent-centric and a non-parent-centric operator. In \[20\]: Copied! ``` composite = CompositeCrossover( problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0, operators=[ SimulatedBinaryCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0), BlendAlphaCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0), ], ) ``` composite = CompositeCrossover( problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0, operators=[ SimulatedBinaryCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0), BlendAlphaCrossover(problem=PROBLEM, publisher=Publisher(), verbosity=1, seed=0), ], ) ## Geometry in two dimensions[¶](#geometry-in-two-dimensions) The combined effect of the probability density in one dimension and the independence of the variables can be seen in two dimensions using scatter plots. In the plot below, two parents sit at [2, 8] and [8, 2]. The above-mentioned crossover operators for continuous variables are applied to them repeatedly, and the resulting offspring are plotted. Each panel shows 1200 offspring. - **Uniform** collapses to the **four corners** of the box the parents span, and to nothing else. Each variable is taken whole from one parent or the other, so the reachable offspring are exactly the combinations of the parents' coordinates. - **Single arithmetic** collapses to just **four points**. It replaces exactly one coordinate with the parent mean and copies the other, so with two variables the only reachable offspring are each parent with one of its coordinates moved to the centre. - **Local** fills the box spanned by the parents, and fills it evenly. Its weight is drawn afresh for each variable, so $x_1$ and $x_2$ are mixed independently and the offspring are uncorrelated. A single shared weight would give the diagonal line instead. Note that local crossover cannot go beyond the bounds of the parents. - **Blend alpha** fills the same kind of box, just a wider one: α pushes the edges out beyond the parents, up to the variable bounds. Note that this only applies if `sample_each_component=True`. - **BEX** stays on regions close to the two parent corners and, at its default $\\lambda = 0.1$. - **SBX** spreads over four regions in roughly equal proportion, the two parent corners and the two opposite ones alike. Its per-variable sign flip takes $x_1$ from one parent and $x_2$ from the other as readily as not, so it recombines the coordinates rather than preserving the parent's combination of them. Its coordinate correlation is essentially zero. This is only applicable if `uniform_xover_probability > 0.0`, which is the default. The value of that argument determines the proportion of offspring that lie in the regions on top of the parents vs the other corners. The more dimensions there are, the more corners there will be. ## Choosing an operator[¶](#choosing-an-operator) | If your variables are… | Use | | ---------------------- | ----------------------------------------------------------------------------- | | continuous | `SimulatedBinaryCrossover` — the default for RVEA, NSGA-III and SMS-EMOA | | binary | `SinglePointBinaryCrossover` | | integer | `UniformIntegerCrossover` | | mixed | `UniformMixedIntegerCrossover` — the default for the mixed-integer algorithms | Within the continuous operators, the choice is about how much exploration you want, and about whether you want the coordinates recombined at all. - `SimulatedBinaryCrossover` and `BoundedExponentialCrossover` both concentrate offspring on the parents, and at their defaults they have almost the same spread. They differ in what they do across variables: SBX mixes coordinates freely between the two parents, while BEX perturbs each parent on its own. Pick SBX when recombination is the point; pick BEX when you would rather explore around existing solutions without scrambling the combinations they represent. - `BlendAlphaCrossover` with a moderate α, and SBX with a small η, explore aggressively. - `LocalCrossover` and `SingleArithmeticCrossover` are conservative and can only contract the population. - `DifferentialEvolutionCrossover` and `ParentCentricCrossover` take their step size from the population rather than from the mating pair. Reach for them when the population's own spread is the scale you want to search at, and for DE in particular when you want a recombination whose behaviour is widely reported in the literature for comparison. One practical note: SBX defaults to `truncated=True`, the formulation used by pymoo, jMetalPy, Platypus and Deb's own NSGA-II code. Pass `truncated=False` for the untruncated formulation that clips instead, as PlatEMO does. Operators can also be selected declaratively, without importing them — see the [Pydantic interface](https://desdeo.readthedocs.io/en/latest/explanation/pydantic_interface): ``` from desdeo.emo.options import crossover options.template.crossover = crossover.BlendAlphaCrossoverOptions(alpha=0.5) ``` ## Implementation details[¶](#implementation-details) Everything below is shared by all nine operators, and is the reason they are interchangeable. **Construction.** Every operator subclasses `BaseCrossover` and is built the same way: ``` operator = SomeCrossover(problem=problem, publisher=publisher, verbosity=1, seed=0, ...) ``` Bounds and types are read from `problem.get_flattened_variables()`, so `TensorVariable`s are handled transparently as flat columns. **Randomness.** Each operator owns a private `numpy` generator seeded from `seed`. There is no shared global random state, so an operator's output depends only on its own seed and call history. **The `do` method.** Keyword-only, and the only method an algorithm calls: ``` offspring = operator.do(population=population, to_mate=None) ``` It returns a `polars.DataFrame` containing **only the decision-variable columns** — objectives and constraints are not carried through. **Pairing.** With `to_mate=None` the whole population is shuffled and paired up. With an explicit `to_mate`, the order is used verbatim, so the caller controls exactly who mates with whom. Pairing is always consecutive: entries $(0,1)$, $(2,3)$, and so on. An odd-length mating pool is padded by repeating its first member, and the resulting extra offspring is discarded — which is why the count always comes out at one offspring per mated parent. **Messages.** Every crossover operator is a `Subscriber` that only ever publishes; none of them subscribes to anything. What is published depends on `verbosity`: | verbosity | published | | --------- | ----------------------------------------------------------------------------------------------- | | 0 | nothing | | 1 | the operator's scalar parameters (`XOVER_PROBABILITY`, `XOVER_DISTRIBUTION`, `ALPHA`, `LAMBDA`) | | 2 | the above plus the `PARENTS` and `OFFSPRINGS` dataframes | Dataframe messages are restricted to verbosity 2 because the message layer only admits scalar payloads at verbosity 1. # Parsing and evaluating problems[¶](#parsing-and-evaluating-problems) In DESDEO, the problem format (c.f., section [The Problem Format](https://desdeo.readthedocs.io/en/latest/explanation/problem_format)) can be parsed into other formats and evaluated. The purpose of evaluating is to allow different solvers, discussed in section [Solvers](https://desdeo.readthedocs.io/en/latest/explanation/solvers), to solve the modeled multiobjective optimization problem. Here, we will first discuss the parsing and the parsers found in DESDEO in section [Parsing and parsers](#parsing-and-parsers). Then, we will discuss the evaluators available in DESDEO for evaluating multiobjective optimization problems in section [Evaluating and evaluators](#evaluating-and-evaluators). After these sections, the reader should have a basic understanding on how the problems defined in DESDEO are evaluated. ## Parsing and parsers[¶](#parsing-and-parsers) ### From the problem format to other formats[¶](#from-the-problem-format-to-other-formats) The most central parsers in DESDEO are those that allow parsing the problem format from the MathJSON format discussed in section [The MathJSON format](https://desdeo.readthedocs.io/en/latest/explanation/problem_format#the-mathjson-format) to other formats that different solvers (i.e., optimizers) can understand. These kind of parsers can be found in the [JSON parser](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.json_parser) module. The [`MathParser`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.json_parser.MathParser) handles parsing of the problem format into a polars format, a pyomo format, a sympy format, or a gurobipy format. In the polars and sympy formats, the problem is represented by polars and sympy expressions. Likewise, in the pyomo and gurobipy formats, the problem is represented as a pyomo or gurobipy model. This allows different solvers to handle the problems we have defined in DESDEO. ### From other formats to the problem format[¶](#from-other-formats-to-the-problem-format) DESDEO has also parsers that allow other formats to be parsed into the MathJSON format representing multiobjective optimization problems. The most notable of these, and the currently only one present, is the infix notation parser found in the [Infix parser](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.infix_parser) module. This allows mathematical expression formatted in a typical infix format, i.e., how one would regularly write a mathematical expression down, e.g., `x * 2 - y`, to the MathJSON format: ``` ["Add", ["Multiply", "x", 2], ["Negate", "y"] ] ``` This is useful when one wants to model a multiobjective optimization problem in DESDEO since it allows the function expression to be written down as they are, without requiring a manual conversion to the MathJSON format first. When adding function expression to the [`Problem` model](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema.Problem), if a `func` field is initialized with a string in an infix format, it is automatically converted to the JSON format utilizing the infix parser. The infix parser can also prove useful when defining various scalarization functions in a dynamic way (c.f., the section [Scalarization](https://desdeo.readthedocs.io/en/latest/explanation/scalarization#scalarization)). Note The infix parser introduces a little bit of overhead. If the parser is utilized to parse infix expressions into the MathJSON format consecutively multiple times, as can be the case with some navigation-based methods, then the overhead might accumulate slowing the method down considerably. In such cases, it is advised to provide the expression directly in the MathJSON format to save time. ## Evaluating and evaluators[¶](#evaluating-and-evaluators) While parsers transform the problem format in DESDEO from one representation to another, evaluators enable the evaluating of a problem, usually by supplying one or more decision variable vectors. Evaluators are not something a user is expected to directly utilize, rather, evaluators are often tied to solvers and solver interfaces, which are discussed in the [Solvers](https://desdeo.readthedocs.io/en/latest/explanation/solvers) section. It is important to understand in which order the various fields found in the problem format (c.f., [The Problem schema](https://desdeo.readthedocs.io/en/latest/explanation/problem_format#the-problem-schema) and [`Problem`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema.Problem)) are evaluated. The first field to be evaluated is the `constants` field, which is made up of [`Constant`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema.Constant) models. Evaluating these fields amounts to replacing the symbol of the constant with its numerical value, or defining an internal variable with the same value. Next, the `extra_funcs` field made up of [`ExtraFunction`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema.ExtraFunction) models is evaluated. This assumes that the extra functions might utilize constants in them, which requires the constants to be available prior to the evaluation. Naturally, evaluating any extra functions is skipped if they are not defined for the problem being evaluated. After the extra functions, the [`Objective`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema.Objective) models, found in the field `objectives` of the problem, are evaluated. These can depend on constants and extra functions, which means that these must have been evaluated prior to evaluating any objectives. Then, any [`Constraint`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema.Constraint) models in the `constraints` field of the problem are evaluated. This assumes that prior to evaluating any constraints, any constants, extra functions, or objectives utilized in the constraint have been evaluated. Objectives might be part of a constraint in, e.g., the epsilon-constraint scalarization. If no constraints have been defined, then this step is skipped. Lastly, any [`ScalarizationFunction`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema.ScalarizationFunction) present in the `scalarizations_funcs` field are evaluated. These can again depend on any of the constants, extra functions, constraints, or objectives defined for the problem. If no scalarization functions have been defined, then their evaluation is skipped. The order of evaluation is important to understand to avoid bugs and unexpected behavior when defining problems in DESDEO. The order of evaluating the fields found in the problem model has been summarized in the list below: 1. Constants, if any. 1. Extra functions, if any. 1. Objective functions. 1. Constraint functions, if any. 1. Scalarization functions, if any. ### The polars evaluator[¶](#the-polars-evaluator) The [`PolarsEvaluator`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.evaluator.PolarsEvaluator) is for evaluating problems to be solved with solvers that expect the problem to be defined as Python functions. It can be utilized in two modes: `variables` or `discrete`. In the first mode, the problem is expected to be evaluated with a given set of decision variable vectors. In the discrete mode, the problem is evaluated based on its discrete representation (c.f., [`DiscreteRepresentation`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema.DiscreteRepresentation)). If the `variables` mode is used, then the function expressions found in the problem are parsed to polars expressions. This allows any Python-based solver to evaluate the problem with given decision variable values. The polars evaluator currently supports scalar variables and one-dimensional TensorVariables (vectors). Higher dimensions on the decision variables are not supported. If the `discrete` mode is used, then the problem is expected to be completely defined by decision and objective vector pairs. When the problem is then evaluated with a given set of decision variable vectors, the closest vectors are searched for in the problem's discrete representation, and the corresponding objective function values are then returned. The discrete evaluator only supports scalar valued variables, not TensorVariables, at the moment. The polars evaluator is utilized by solvers that do not expect, or require, the exact formulation of the problem. That is, heuristics based and gradient-free solvers. At the moment, these solvers implemented in DESDEO are the [Scipy solvers](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#scipy-solver-interfaces) and the [`ProximalSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#proximal-solver). Info For more info about polars, see [the polars documentation](https://pola.rs/). ### The pyomo evaluator[¶](#the-pyomo-evaluator) The [`PyomoEvaluator`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.pyomo_evaluator.PyomoEvaluator) transforms a problem into a pyomo model. This enables the usage of many external solvers, such as the ones found in the [COIN-OR project](https://www.coin-or.org/) to be utilized in DESDEO. Unlike the polars evaluator, the pyomo evaluator does not expect decision variables, instead, it provides a pyomo model that external solvers can then utilize to solve the original problem. The pyomo solvers implemented in DESDEO can be found in the [pyomo solver interfaces](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#pyomo-solver-interfaces). The pyomo evaluator supports variables that are higher dimensional tensors (TensorVariables) as well. Note Currently, the pyomo evaluator utilized only concrete pyomo models (ConcreteModel). Info For more info about pyomo, see [the pyomo documentation](https://pyomo.readthedocs.io/en/stable/). ### The sympy evaluator[¶](#the-sympy-evaluator) The [`SympyEvaluator`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.sympy_evaluator.SympyEvaluator) parses a problem into sympy expressions using [`MathParser`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.json_parser.MathParser). The parsed expressions are then compiled into callable Python functions via `sympy.lambdify()`, which allows for fast numerical evaluation. The sympy evaluator evaluates the problem one decision variable vector at a time (single-sample evaluation). It only supports scalar variables — TensorVariables are not supported. Constants, extra functions, objectives, constraints, and scalarization functions are all handled by substituting the relevant sympy expressions into one another during initialization. The sympy evaluator is currently used by the [`NevergradGenericSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.ng_solver_interfaces.NevergradGenericSolver) for gradient-free optimization. Beyond evaluation, the use of sympy opens potential for symbolic operations such as symbolic differentiation, simplification, and LaTeX export. Contributions are welcome! Info For more info about sympy, see [the sympy documentation](https://docs.sympy.org/latest/). ### The gurobipy evaluator[¶](#the-gurobipy-evaluator) The [`GurobipyEvaluator`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.gurobipy_evaluator.GurobipyEvaluator) transforms a problem into a Gurobipy model. This model is then used in optimization through the [`GurobipySolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.gurobipy_solver_interfaces.GurobipySolver). The gurobipy evaluator supports variables that are higher dimensional tensors (TensorVariables) as well. Info For more info about gurobi, see [the gurobi documentation](https://www.gurobi.com/documentation/). ### The simulator evaluator[¶](#the-simulator-evaluator) The [`SimulatorEvaluator`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.simulator_evaluator.SimulatorEvaluator) adds support for simulator and surrogate based objectives, constraints and extra functions. This is done by collecting the simulators and surrogates in the evaluator and calling them by providing the decision variables and parameters needed. The connection to simulators happens via [simulator files](https://desdeo.readthedocs.io/en/latest/explanation/simulator_support#simulator-file). The surrogate models are loaded from disk and then evaluated with the given decision variable values. This evaluator also handles analytical functions by calling the [PolarsEvaluator](#the-polars-evaluator). #### Evaluating simulator and surrogate based problems[¶](#evaluating-simulator-and-surrogate-based-problems) [`SimulatorEvaluator`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.simulator_evaluator.SimulatorEvaluator) can be used to evaluate any problems with analytical, simulator and surrogate based objectives, constraints and extra functions. In what follows, it is explained, how the evaluator works. [Here](https://desdeo.readthedocs.io/en/latest/howtoguides/problem#example-simulation-based-problem) is an example of defining a simulator based problem in DESDEO. First, we need to initialize the problem we are solving: In \[1\]: Copied! ``` import tempfile import warnings from pathlib import Path import joblib from sklearn.datasets import make_friedman2, make_gaussian_quantiles from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel from sklearn.linear_model import LogisticRegression from desdeo.problem.testproblems import simulator_problem # Create the test problem with analytical, simulator, and surrogate objectives problem = simulator_problem("../../tests/data") # Create temporary surrogate model files for the surrogate-based objectives tmpdir = Path(tempfile.mkdtemp()) with warnings.catch_warnings(): warnings.simplefilter("ignore") X1, y1 = make_friedman2(n_samples=500, noise=0, random_state=0) gpr = GaussianProcessRegressor(kernel=DotProduct() + WhiteKernel(), random_state=0).fit(X1, y1) surrogate_path_1 = tmpdir / "surr1" / "model.pkl" surrogate_path_1.parent.mkdir() joblib.dump(gpr, surrogate_path_1) X2, y2 = make_gaussian_quantiles(n_samples=500, n_features=4, random_state=0) lr = LogisticRegression(random_state=0).fit(X2, y2) surrogate_path_2 = tmpdir / "surr2" / "model.pkl" surrogate_path_2.parent.mkdir() joblib.dump(lr, surrogate_path_2) ``` import tempfile import warnings from pathlib import Path import joblib from sklearn.datasets import make_friedman2, make_gaussian_quantiles from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel from sklearn.linear_model import LogisticRegression from desdeo.problem.testproblems import simulator_problem # Create the test problem with analytical, simulator, and surrogate objectives problem = simulator_problem("../../tests/data") # Create temporary surrogate model files for the surrogate-based objectives tmpdir = Path(tempfile.mkdtemp()) with warnings.catch_warnings(): warnings.simplefilter("ignore") X1, y1 = make_friedman2(n_samples=500, noise=0, random_state=0) gpr = GaussianProcessRegressor(kernel=DotProduct() + WhiteKernel(), random_state=0).fit(X1, y1) surrogate_path_1 = tmpdir / "surr1" / "model.pkl" surrogate_path_1.parent.mkdir() joblib.dump(gpr, surrogate_path_1) X2, y2 = make_gaussian_quantiles(n_samples=500, n_features=4, random_state=0) lr = LogisticRegression(random_state=0).fit(X2, y2) surrogate_path_2 = tmpdir / "surr2" / "model.pkl" surrogate_path_2.parent.mkdir() joblib.dump(lr, surrogate_path_2) Out\[1\]: ``` ['/tmp/tmpjd0ifqc4/surr2/model.pkl'] ``` The problem we defined has at least some simulator or surrogate based objectives, constraints or extra functions. Therefore, we should use `SimulatorEvaluator` to evaluate it. To use the evaluator, we first need to initialize it. When initializing the evaluator, we give the problem as an argument. We can also give the evaluator some optional additional arguments: - `params`: Some parameters for the simulators as a python dict of dicts. For example, In \[2\]: Copied! ``` {"s_1": {"alpha": 0.1, "beta": 0.2}, "s_2": {"epsilon": 10, "gamma": 20}} ``` {"s_1": {"alpha": 0.1, "beta": 0.2}, "s_2": {"epsilon": 10, "gamma": 20}} Out\[2\]: ``` {'s_1': {'alpha': 0.1, 'beta': 0.2}, 's_2': {'epsilon': 10, 'gamma': 20}} ``` where `s_1` and `s_2` are symbols of two simulators and the corresponding values are dicts with some parameter values for the corresponding simulators. These parameter values are passed to the simulators. - `surrogate_paths`: Paths to surrogate files stored on disk. Given as a python dict with objective, constraint or extra function symbols as keys and the corresponding surrogate paths as values of the dict. The surrogate file path can be given as either a string of the path or a `pathlib.Path` object. This is an optional argument and if not defined, the evaluator uses surrogate models in the problem object, if available. With these arguments we can then import and initialize the evaluator. In \[3\]: Copied! ``` from desdeo.problem import SimulatorEvaluator evaluator = SimulatorEvaluator( problem=problem, params={ "s_1": {"alpha": 0.1, "beta": 0.2}, "s_2": {"epsilon": 10, "gamma": 20}, }, surrogate_paths={ "f_5": surrogate_path_1, "f_6": surrogate_path_2, "g_3": surrogate_path_1, "e_3": surrogate_path_2, }, ) ``` from desdeo.problem import SimulatorEvaluator evaluator = SimulatorEvaluator( problem=problem, params={ "s_1": {"alpha": 0.1, "beta": 0.2}, "s_2": {"epsilon": 10, "gamma": 20}, }, surrogate_paths={ "f_5": surrogate_path_1, "f_6": surrogate_path_2, "g_3": surrogate_path_1, "e_3": surrogate_path_2, }, ) As the evaluator is initialized, it calls the `_load_surrogates` method that loads the surrogate models from the disk. If no surrogate paths are passed to the evaluator, it takes the surrogate paths from the problem, if possible. Now that the evaluator is initialized, we can call its `evaluate` method. The method takes one argument `xs` that is a dict that has the problem's decision variables and some values for them that we would like to evaluate the problem with. Say we have four decision variables and we would like to evaluate five samples. Then, the dict of decision variables would have the decision variable symbols as keys and the corresponding values would be lists of decision variable values with a single value for each sample (length of each list in this example would be five). Then we would define the decision variable dict and call the evaluate method as follows. Note All the decision variable value lists should be the same length, i.e., same number of samples given of each decision variable. In \[4\]: Copied! ``` xs = { "x_1": [0, 1, 2, 3, 4], "x_2": [4, 3, 2, 1, 0], "x_3": [0, 4, 1, 3, 2], "x_4": [3, 1, 3, 2, 3], } results = evaluator.evaluate(xs) results ``` xs = { "x_1": [0, 1, 2, 3, 4], "x_2": [4, 3, 2, 1, 0], "x_3": [0, 4, 1, 3, 2], "x_4": [3, 1, 3, 2, 3], } results = evaluator.evaluate(xs) results Out\[4\]: shape: (5, 26) | x_1 | x_2 | x_3 | x_4 | e_2 | f_2 | f_2_min | g_2 | f_1 | f_4 | e_1 | f_3 | g_1 | f_1_min | f_3_min | f_4_min | f_5 | f_5_uncert | f_6 | f_6_uncert | g_3 | g_3_uncert | e_3 | e_3_uncert | f_5_min | f_6_min | | --- | --- | --- | --- | ---- | --- | ------- | ---- | --- | --- | --- | ---- | ---- | ------- | ------- | ------- | -------- | ---------- | --- | ---------- | -------- | ---------- | --- | ---------- | -------- | ------- | | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | f64 | i64 | f64 | f64 | f64 | i64 | f64 | f64 | i64 | | 0.0 | 4.0 | 0.0 | 3.0 | 0.0 | 4.0 | -4.0 | -4.0 | 0.4 | 8.0 | 2.0 | -4.5 | 8.2 | 0.4 | 4.5 | 8.0 | 0.873036 | 316.240953 | 2 | NaN | 0.873036 | 316.240953 | 2 | NaN | 0.873036 | 2 | | 1.0 | 3.0 | 4.0 | 1.0 | 12.0 | 8.0 | -8.0 | -8.0 | 2.3 | 6.2 | 1.5 | -1.5 | 5.2 | 2.3 | 1.5 | 6.2 | 3.083028 | 316.254497 | 0 | NaN | 3.083028 | 316.254497 | 0 | NaN | 3.083028 | 0 | | 2.0 | 2.0 | 1.0 | 3.0 | 4.0 | 5.0 | -5.0 | -5.0 | 4.2 | 4.4 | 1.0 | 1.5 | 2.2 | 4.2 | -1.5 | 4.4 | 0.889159 | 316.242774 | 2 | NaN | 0.889159 | 316.242774 | 2 | NaN | 0.889159 | 2 | | 3.0 | 1.0 | 3.0 | 2.0 | 9.0 | 7.0 | -7.0 | -7.0 | 6.1 | 2.6 | 0.5 | 4.5 | -0.8 | 6.1 | -4.5 | 2.6 | 1.893414 | 316.249087 | 0 | NaN | 1.893414 | 316.249087 | 0 | NaN | 1.893414 | 0 | | 4.0 | 0.0 | 2.0 | 3.0 | 0.0 | 6.0 | -6.0 | -6.0 | 8.0 | 0.8 | 0.0 | 7.5 | -3.8 | 8.0 | -7.5 | 0.8 | 0.905282 | 316.249614 | 0 | NaN | 0.905282 | 316.249614 | 0 | NaN | 0.905282 | 0 | The evaluator returns a polars Dataframe with each decision variable, objective, constraint and extra function as their own column. ## Where to go next?[¶](#where-to-go-next) You can keep studying the various parsers found in the modules [JSON parser](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.json_parser) and [Infix parser](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.infix_parser), and the evaluators found in the modules [Polars evaluator](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.evaluator), [Pyomo evaluator](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.pyomo_evaluator), [Sympy evaluator](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.sympy_evaluator), [Gurobipy evaluator](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.gurobipy_evaluator), and [Simulator evaluator](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.simulator_evaluator). If you are interested in how to solve a multiobjective optimization problem, then the section [Scalarization](https://desdeo.readthedocs.io/en/latest/explanation/scalarization) is a good place to check out. # The Problem format[¶](#the-problem-format) Multiobjective optimization problems are represented by pydantic dataclasses in DESDEO. These are serializable and therefore easy to store. Moreover, they can be readily transformed into JSON objects, which makes passing them from DESDEO's web-API to various frontend applications seamless. This also facilitates the parsing of the problem format into other formats as well. While representing problems as pydantic dataclasses comes with some overhead, this is justified by the utility and robustness of the pydantic dataclasses. One of the challenges with this kind of representation is representing function expression. These have been taken care by exploiting the MathJSON format, which is described in more details in the section [The MathJSONformat](#the-mathjson-format). The pydantic dataclass for representing a multiobjective optimization problem in DESDEO is discussed in the section [The Problem schema](#the-problem-schema), where the structure, or schema, of the dataclass is described in detail. ## The MathJSON format[¶](#the-mathjson-format) MathJSON is a lightweight, JSON-based format designed for representing mathematical expressions in a structured and easily parsable manner. It provides a standardized way to represent mathematical notation within JSON objects. Moreover, it allows users to define mathematical formulations in web-based frontend applications, which can then be directly represented in the DESDEO problem schema. In DESDEO, the MathJSON format is utilized to represent function expression found throughout the problem schema. MathJSON follows Polish notation, which means that mathematical operators precede the operands when defining mathematical expressions. As an example, consider the following expression: $$ \\max(x, y ,z) + \\frac{y}{z} - \\sin\\left(z^x + 4.2\\right)^3, $$ where x, y, and x are some variables. The equivalent of this expression in the MathJSON format (Polish notation), would be: ``` [ "Add", ["Divide", "y", "z"], ["Max", "x", "y", "z"], [ "Negate", ["Power", ["Sin", ["Add", ["Power", "z", "x"], 4.2]], 3] ] ] ``` At first glance, this may look overly complicated, but from a programming perspective, parsing Polish notation is much simpler than infix notation, e.g., "normal" notation, where the operations are between the operands. The MathJSON notation is utilized for all function expressions found in the problem schema in DESDEO. For more information on the MathJSON format, see the [MathJSON project](https://cortexjs.io/math-json/). ## The Problem schema[¶](#the-problem-schema) Here, the structure of the problem dataclass, or the schema, is presented in detail. The `Problem` dataclass itself is constructed from other dataclasses contained in its field. We will refer to the schemas as *models* from thereon. ### The symbol field[¶](#the-symbol-field) Across many of the models found in the `Problem` dataclass, the field `symbol` will be often present. This field is very important, because it is utilized to identify variables and function expression across the `Problem` model. Therefore, the `symbol` field should contain a symbol that is unique across the whole `Problem` model. The symbol itself is nothing more than a string value. Some symbol names are reserved in DESDEO, and users should avoid defining variables or function expression with these symbols. Reserved symbols are discussed in the section [Symbols and expressions](#symbols-and-expressions). ### The scenario keys field[¶](#the-scenario-keys-field) As with the `symbol` field, the `scenario_keys` is also a recurring field across the `Problem` model. This field is used to indicate to which scenario, or scenarios, a field (e.g., representing an objective function) belongs to. The `scenario_keys` is a list of strings and is optional. When its value is `None` is means that it belongs to all defined scenarios, or no scenarios at all if the problem has no defined scenarios. The `Problem` model itself has also the field `scenario_keys`, which is used indicate which scenarios haven been defined for the `Problem`. When this field is `None`, it means the `Problem` has no defined scenarios. ### Common fields for computable models[¶](#common-fields-for-computable-models) The computable models that are used to construct a `Problem` all have some common fields defined for them. The computable models are `Objective`, `Constraint`, `ExtraFunction`, and `ScalarizationFunction`. These fields generally represent something that can be evaluated, and is likely to be optimized at some point, either directly, or indirectly, e.g., as part of a scalarization. The common fields are: - `is_linear`: is the model linear? - `is_convex`: is the model convex? - `is_twice_differentiable`: is the model twice continuously differentiable? These are all assumed to be `False` by default. The listed fields play an important role in the selection of optimizer when the `Problem` model is being solved. ### Problem[¶](#problem) The main dataclass storing information related to a multiobjective optimization is the `Problem` model, which consists of other models. The `Problem` model itself consists of the following fields: - `name`: the name of the problem, - `description`: the description of the problem, - `constants`: a list of constant utilized in the definition of the problem, - `variables`: a list of the variables of the problem, - `objectives`: a list of the objective functions of the problem, - `constraints`: an optional list of the constraints of the problem, - `extra_funcs`: an optional list of extra functions utilized in defining the problem, - `scalarization_funcs`: an optional list of scalarized representations of the problem, - `discrete_representation`: an optional representation of the problem as discrete decision variable vector and objective vector pairs, and - `scenario_keys`: an optional list of scenario keys. The **name** and **description** of the problem are just strings. The other fields consist of one or more additional models, or Python types, such as lists. These will be described next. Note The symbol entries across all fields must be unique. If one or more non-unique symbols are defined, Problem will raise an error when being initialized. Note The Problem model and all its field are immutable. The only exception to this is the symbol field of the ScalarizationFunction models. ### Constant[¶](#constant) The `Constant` model defines a constant with the fields `name`, `symbol` and `value`. The field `name` is the name of the constant, for example "Price", the `symbol` is the constant's mathematical symbol, for example "c_1", and the `value` represents the numerical value of the constant, for example 4.2. The JSON schema of `Constant` looks as follows: **Click to expand** ``` { "description": "Model for a constant.", "properties": { "name": { "description": "Descriptive name of the constant. This can be used in UI and visualizations. Example: 'maximum cost'.", "title": "Name", "type": "string" }, "symbol": { "description": "Symbol to represent the constant. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'c_1'.", "title": "Symbol", "type": "string" }, "value": { "anyOf": [ { "type": "number" }, { "type": "integer" }, { "type": "boolean" } ], "description": "The value of the constant.", "title": "Value" } }, "required": [ "name", "symbol", "value" ], "title": "Constant", "type": "object" } ``` and an example of the JSON object corresponding to the schema looks like: **Click to expand** ``` { "name": "constant example", "symbol": "c", "value": 42.1 } ``` ### TensorConstant[¶](#tensorconstant) The `TensorConstant` model defines an indexed constant with the fields `name`, `symbol`, `shape`, and `values`. The `name is the name of the constant, for example "Weights", the` symbol`is the constant's mathematical symbol, for example "A",`shape`defines the sizes of the dimensions of the constant, and`values`defines the values represented by the constant.`TensorConstant\` is an indexed value, which means it can represent tensors, such as vectors and matrices. The JSON schema of `TensorConstant` looks as follows: **Click to expand** ``` { "$defs": { "Tensor": { "anyOf": [ { "items": { "$ref": "/$defs/Tensor" }, "type": "array" }, { "items": { "anyOf": [ { "type": "number" }, { "type": "integer" }, { "type": "boolean" } ] }, "type": "array" }, { "type": "number" }, { "type": "integer" }, { "type": "boolean" }, { "const": "List", "enum": [ "List" ], "type": "string" }, { "type": "null" } ] } }, "description": "Model for a tensor containing constant values.", "properties": { "name": { "description": "Descriptive name of the tensor representing the values. E.g., 'distances'", "title": "Name", "type": "string" }, "symbol": { "description": "Symbol to represent the constant. This will be used in the rest of the problem definition. Notice that the elements of the tensor will be represented with the symbol followed by indices. E.g., the first element of the third element of a 2-dimensional tensor, is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable. Note that indexing starts from 1.", "title": "Symbol", "type": "string" }, "shape": { "description": "A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns.", "items": { "type": "integer" }, "title": "Shape", "type": "array" }, "values": { "$ref": "/$defs/Tensor", "description": "A list of lists, with the elements representing the values of each constant element in the tensor. E.g., `[[5, 22, 0], [14, 5, 44]]`." } }, "required": [ "name", "symbol", "shape", "values" ], "title": "TensorConstant", "type": "object" } ``` and an example of the JSON object corresponding to the schema looks like: **Click to expand** ``` { "name": "tensor constant example", "symbol": "t_c", "shape": [ 2 ], "values": [ "List", 40, 50 ] } ``` ### Variable[¶](#variable) The `Variable` model defines a decision variable with the fields `name`, `symbol`, `variable_type`, `lowerbound`, `upperbound`, and `initial_value`. The `name` and `symbol` represent the name and mathematical symbol of the variable. The field `variable_type` represents the variable's type, either "real", "integer", or "binary". Lastly, the `initial_value` field is the initial value of the variable. This can be used by some optimizers found in DESDEO in finding an optimal solution to, e.g., a scalarized variant of the problem. The JSON schema `Variable` looks as follows: **Click to expand** ``` { "$defs": { "VariableTypeEnum": { "description": "An enumerator for possible variable types.", "enum": [ "real", "integer", "binary" ], "title": "VariableTypeEnum", "type": "string" } }, "description": "Model for a variable.", "properties": { "name": { "description": "Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'.", "title": "Name", "type": "string" }, "symbol": { "description": "Symbol to represent the variable. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'v_1'.", "title": "Symbol", "type": "string" }, "variable_type": { "$ref": "/$defs/VariableTypeEnum", "description": "Type of the variable. Can be real, integer or binary." }, "lowerbound": { "anyOf": [ { "type": "number" }, { "type": "integer" }, { "type": "boolean" }, { "type": "null" } ], "default": null, "description": "Lower bound of the variable.", "title": "Lowerbound" }, "upperbound": { "anyOf": [ { "type": "number" }, { "type": "integer" }, { "type": "boolean" }, { "type": "null" } ], "default": null, "description": "Upper bound of the variable.", "title": "Upperbound" }, "initial_value": { "anyOf": [ { "type": "number" }, { "type": "integer" }, { "type": "boolean" }, { "type": "null" } ], "default": null, "description": "Initial value of the variable. This is optional.", "title": "Initial Value" } }, "required": [ "name", "symbol", "variable_type" ], "title": "Variable", "type": "object" } ``` and an example of the JSON object corresponding to the schema looks like: **Click to expand** ``` { "name": "variable example", "symbol": "x", "variable_type": "real", "lowerbound": 0, "upperbound": 1, "initial_value": 0.5 } ``` ### TensorVariable[¶](#tensorvariable) The `TensorVariable` model defines a decision variable with the fields `name`, `symbol`, `variable_type`, `shape`, `lowerbounds`, `upperbounds`, and `initial_values`. The `name` and `symbol` represent the name and mathematical symbol of the variable. The field `variable_type` represents the variable's element types, either "real", "integer", or "binary". Lastly, the `initial_values` field defines the initial values contained in the variable. This information can be used by some optimizers found in DESDEO in finding an optimal solution to, e.g., a scalarized variant of the problem the variable is part of. `TensorVariable` is an indexed value, which means it can represent tensors, such as vectors and matrices. The JSON schema `TensorVariable` looks as follows: **Click to expand** ``` { "$defs": { "Tensor": { "anyOf": [ { "items": { "$ref": "/$defs/Tensor" }, "type": "array" }, { "items": { "anyOf": [ { "type": "number" }, { "type": "integer" }, { "type": "boolean" } ] }, "type": "array" }, { "type": "number" }, { "type": "integer" }, { "type": "boolean" }, { "const": "List", "enum": [ "List" ], "type": "string" }, { "type": "null" } ] }, "VariableTypeEnum": { "description": "An enumerator for possible variable types.", "enum": [ "real", "integer", "binary" ], "title": "VariableTypeEnum", "type": "string" } }, "description": "Model for a tensor, e.g., vector variable.", "properties": { "name": { "description": "Descriptive name of the variable. This can be used in UI and visualizations. Example: 'velocity'.", "title": "Name", "type": "string" }, "symbol": { "description": "Symbol to represent the variable. This will be used in the rest of the problem definition. Notice that the elements of the tensor will be represented with the symbol followed by indices. E.g., the first element of the third element of a 2-dimensional tensor, is represented by 'x_1_3', where 'x' is the symbol given to the TensorVariable. Note that indexing starts from 1.", "title": "Symbol", "type": "string" }, "variable_type": { "$ref": "/$defs/VariableTypeEnum", "description": "Type of the variable. Can be real, integer, or binary. Note that each element of a TensorVariable is assumed to be of the same type." }, "shape": { "description": "A list of the dimensions of the tensor, e.g., `[2, 3]` would indicate a matrix with 2 rows and 3 columns.", "items": { "type": "integer" }, "title": "Shape", "type": "array" }, "lowerbounds": { "anyOf": [ { "$ref": "/$defs/Tensor" }, { "type": "null" } ], "default": null, "description": "A list of lists, with the elements representing the lower bounds of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the lower bound of each element. Defaults to None." }, "upperbounds": { "anyOf": [ { "$ref": "/$defs/Tensor" }, { "type": "number" }, { "type": "integer" }, { "type": "boolean" }, { "type": "null" } ], "default": null, "description": "A list of lists, with the elements representing the upper bounds of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the upper bound of each element. Defaults to None.", "title": "Upperbounds" }, "initial_values": { "anyOf": [ { "$ref": "/$defs/Tensor" }, { "type": "number" }, { "type": "integer" }, { "type": "boolean" }, { "type": "null" } ], "default": null, "description": "A list of lists, with the elements representing the initial values of each element. E.g., `[[1, 2, 3], [4, 5, 6]]`. If a single value is supplied, that value is assumed to be the initial value of each element. Defaults to None.", "title": "Initial Values" } }, "required": [ "name", "symbol", "variable_type", "shape" ], "title": "TensorVariable", "type": "object" } ``` and an example of the JSON object corresponding to the schema looks like: **Click to expand** ``` { "name": "tensor variable example", "symbol": "X", "variable_type": "integer", "shape": [ 3 ], "lowerbounds": [ "List", 1, 2, 3 ], "upperbounds": [ "List", 10, 20, 30 ], "initial_values": [ "List", 1, 1, 1 ] } ``` ### Objective[¶](#objective) The `Objective` model defines an objective function with the fields `name`, `symbol`, `func`, `maximized`, `ideal`, `nadir`, and `objective_type`. The `name` and `symbol` represent the objective's name and mathematical symbol. The field `func` represents the objective's mathematical, or analytical, formulation. This can be given either in the MathJSON format, or it may also be supplied in infix, e.g., "normal", notation. In the case of the latter, the expression will be parsed into the MathJSON format. The field `maximized` indicated whether the objective function is to be maximized or not. By default, this field is assumed to be false, i.e., objective functions are assumed to be minimized in DESDEO unless it is explicitly specified that maximization is desired. The fields `ideal` and `nadir` are the objective function's ideal and nadir points, respectively. These are also optional, but supplying them, if known, can expedite the execution of some methods in DESDEO. Lastly, `objective_type` is the type of the objective functions. Currently, this can be either "analytical" or "data_based". In the latter case, the `func` field may be left empty, but it is then expected that a `DiscreteRepresentation` for the objective is available in the `Problem` model. See the subsection [DiscreteRepresentation](#discreterepresentation). The JSON schema of `Objective` looks as follows: **Click to expand** ``` { "$defs": { "ObjectiveTypeEnum": { "description": "An enumerator for supported objective function types.", "enum": [ "analytical", "data_based", "simulator", "surrogate" ], "title": "ObjectiveTypeEnum", "type": "string" } }, "description": "Model for an objective function.", "properties": { "name": { "description": "Descriptive name of the objective function. This can be used in UI and visualizations. Example: 'time'.", "title": "Name", "type": "string" }, "symbol": { "description": "Symbol to represent the objective function. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'f_1'.", "title": "Symbol", "type": "string" }, "unit": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null, "description": "The unit of the objective function. This is optional. Used in UIs and visualizations. Example: 'seconds' or 'millions of hectares'.", "title": "Unit" }, "func": { "anyOf": [ { "items": {}, "type": "array" }, { "type": "null" } ], "default": null, "description": "The objective function. This is a JSON object that can be parsed into a function.Must be a valid MathJSON object. The symbols in the function must match the symbols defined for variable/constant/extra function. Can be 'None' for 'data_based', 'simulator' or 'surrogate' objective functions. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'.", "title": "Func" }, "simulator_path": { "anyOf": [ { "format": "path", "type": "string" }, { "type": "null" } ], "default": null, "description": "Path to a python file with the connection to simulators. Must be a valid Path.Can be 'None' for 'analytical', 'data_based' or 'surrogate' objective functions.If 'None', either 'func' or 'surrogates' must not be 'None'.", "title": "Simulator Path" }, "surrogates": { "anyOf": [ { "items": { "format": "path", "type": "string" }, "type": "array" }, { "type": "null" } ], "default": null, "description": "A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based or 'simulator' objective functions. If 'None', either 'func' or 'simulator_path' must not be 'None'.", "title": "Surrogates" }, "maximize": { "default": false, "description": "Whether the objective function is to be maximized or minimized.", "title": "Maximize", "type": "boolean" }, "ideal": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "default": null, "description": "Ideal value of the objective. This is optional.", "title": "Ideal" }, "nadir": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "default": null, "description": "Nadir value of the objective. This is optional.", "title": "Nadir" }, "objective_type": { "$ref": "/$defs/ObjectiveTypeEnum", "default": "analytical", "description": "The type of objective function. 'analytical' means the objective function value is calculated based on 'func'. 'data_based' means the objective function value should be retrieved from a table. In case of 'data_based' objective function, the 'func' field is ignored. Defaults to 'analytical'." }, "is_linear": { "default": false, "description": "Whether the function expression is linear or not. Defaults to `False`.", "title": "Is Linear", "type": "boolean" }, "is_convex": { "default": false, "description": "Whether the function expression is convex or not (non-convex). Defaults to `False`.", "title": "Is Convex", "type": "boolean" }, "is_twice_differentiable": { "default": false, "description": "Whether the function expression is twice differentiable or not. Defaults to `False`", "title": "Is Twice Differentiable", "type": "boolean" }, "scenario_keys": { "anyOf": [ { "items": { "type": "string" }, "type": "array" }, { "type": "null" } ], "default": null, "description": "Optional. The keys of the scenarios the objective function belongs to.", "title": "Scenario Keys" } }, "required": [ "name", "symbol" ], "title": "Objective", "type": "object" } ``` and an example of the JSON object corresponding to the schema looks like: **Click to expand** ``` { "name": "objective example", "symbol": "f", "unit": null, "func": [ "Add", "x", 1 ], "simulator_path": null, "surrogates": null, "maximize": false, "ideal": null, "nadir": null, "objective_type": "analytical", "is_linear": true, "is_convex": false, "is_twice_differentiable": false, "scenario_keys": null } ``` ### Constraint[¶](#constraint) The `Constraint` model defines a constraint function with the fields `name`, `symbol`, `cons_type`, `linear` and `func`. The `name` and `symbol` represent the constraint's name and mathematical symbol, respectively. The field `cons_type` represents the type of constraint. Currently, the type can be either "\<=" for inequality constraints, or "=" for equality constraints. Lastly, `func` is the mathematical representation of the constraint function. This can be supplied either in the MathJSON format or in "normal" infix format. As for how the constraint should be defined, see the note below. Note The constraint is expected in a standard format where the function expression of the constraint is on the left hand side of an inequality expression, and on the right hand side a zero is assumed. Likewise, for equality constraints, the left hand side has a function expression that must be equal to zero. In other words, a constraint, such as `x_1 <= 5` must first be expressed as `x_1 - 5 <= 0`, and then the constraint expression supplied to the `Constraint` model would be `x_1 - 5`. Likewise, an equality constraint, such as `x_1 + x_2 == 5` would be first expressed as `x_1 + x_2 - 5 == 0`, and the supplied function expression would be `x_1 + x_2 - 5`. Its JSON schema of `Constraint` looks as follows: **Click to expand** ``` { "$defs": { "ConstraintTypeEnum": { "description": "An enumerator for supported constraint expression types.", "enum": [ "=", "<=" ], "title": "ConstraintTypeEnum", "type": "string" } }, "description": "Model for a constraint function.", "properties": { "name": { "description": "Descriptive name of the constraint. This can be used in UI and visualizations. Example: 'maximum length'.", "title": "Name", "type": "string" }, "symbol": { "description": "Symbol to represent the constraint. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'g_1'.", "title": "Symbol", "type": "string" }, "cons_type": { "$ref": "/$defs/ConstraintTypeEnum", "description": "The type of the constraint. Constraints are assumed to be in a standard form where the supplied 'func' expression is on the left hand side of the constraint's expression, and on the right hand side a zero value is assume. The comparison between the left hand side and right hand side is either and quality comparison ('=') or lesser than equal comparison ('<=')." }, "func": { "anyOf": [ { "items": {}, "type": "array" }, { "type": "null" } ], "default": null, "description": "Function of the constraint. This is a JSON object that can be parsed into a function.Must be a valid MathJSON object. The symbols in the function must match objective/variable/constant symbols.Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'.", "title": "Func" }, "simulator_path": { "anyOf": [ { "format": "path", "type": "string" }, { "type": "null" } ], "default": null, "description": "Path to a python file with the connection to simulators. Must be a valid Path.Can be 'None' for if either 'func' or 'surrogates' is not 'None'.If 'None', either 'func' or 'surrogates' must not be 'None'.", "title": "Simulator Path" }, "surrogates": { "anyOf": [ { "items": { "format": "path", "type": "string" }, "type": "array" }, { "type": "null" } ], "default": null, "description": "A list of paths to models saved on disk. Can be 'None' for if either 'func' or 'simulator_path' is not 'None'. If 'None', either 'func' or 'simulator_path' must not be 'None'.", "title": "Surrogates" }, "is_linear": { "default": true, "description": "Whether the constraint is linear or not. Defaults to True, e.g., a linear constraint is assumed.", "title": "Is Linear", "type": "boolean" }, "is_convex": { "default": false, "description": "Whether the function expression is convex or not (non-convex). Defaults to `False`.", "title": "Is Convex", "type": "boolean" }, "is_twice_differentiable": { "default": false, "description": "Whether the function expression is twice differentiable or not. Defaults to `False`", "title": "Is Twice Differentiable", "type": "boolean" }, "scenario_keys": { "anyOf": [ { "items": { "type": "string" }, "type": "array" }, { "type": "null" } ], "default": null, "description": "Optional. The keys of the scenarios the constraint belongs to.", "title": "Scenario Keys" } }, "required": [ "name", "symbol", "cons_type" ], "title": "Constraint", "type": "object" } ``` and an example of the JSON object corresponding to the schema looks like: **Click to expand** ``` { "name": "example constrant", "symbol": "g", "cons_type": "<=", "func": [ "Add", "x", [ "Negate", "c" ] ], "simulator_path": null, "surrogates": null, "is_linear": true, "is_convex": false, "is_twice_differentiable": false, "scenario_keys": null } ``` ### ExtraFunction[¶](#extrafunction) The `ExtraFunction` model defines any functions utilized in the definition of the problem. The extra function has the fields `name`, `symbol`, and `func`. The fields `name` and `symbol` represent the extra function's name and mathematical symbol, respectively. The field `func` is the mathematical representation of the extra function, which must be supplied either in the MathJSON format, or in the "normal" infix notation. The JSON schema of `ExtraFunction` looks as: **Click to expand** ``` { "description": "Model for extra functions.\n\nThese functions can, e.g., be functions that are re-used in the problem formulation, or\nthey are needed for other computations related to the problem.", "properties": { "name": { "description": "Descriptive name of the function. Example: 'normalization'.", "title": "Name", "type": "string" }, "symbol": { "description": "Symbol to represent the function. This will be used in the rest of the problem definition. It may also be used in UIs and visualizations. Example: 'avg'.", "title": "Symbol", "type": "string" }, "func": { "anyOf": [ { "items": {}, "type": "array" }, { "type": "null" } ], "default": null, "description": "The string representing the function. This is a JSON object that can be parsed into a function.Must be a valid MathJSON object. The symbols in the function must match symbols defined for objective/variable/constant.Can be 'None' if either 'simulator_path' or 'surrogates' is not 'None'. If 'None', either 'simulator_path' or 'surrogates' must not be 'None'.", "title": "Func" }, "simulator_path": { "anyOf": [ { "format": "path", "type": "string" }, { "type": "null" } ], "default": null, "description": "Path to a python file with the connection to simulators. Must be a valid Path.Can be 'None' for 'analytical', 'data_based' or 'surrogate' functions.If 'None', either 'func' or 'surrogates' must not be 'None'.", "title": "Simulator Path" }, "surrogates": { "anyOf": [ { "items": { "format": "path", "type": "string" }, "type": "array" }, { "type": "null" } ], "default": null, "description": "A list of paths to models saved on disk. Can be 'None' for 'analytical', 'data_based or 'simulator' functions. If 'None', either 'func' or 'simulator_path' must not be 'None'.", "title": "Surrogates" }, "is_linear": { "default": false, "description": "Whether the function expression is linear or not. Defaults to `False`.", "title": "Is Linear", "type": "boolean" }, "is_convex": { "default": false, "description": "Whether the function expression is convex or not (non-convex). Defaults to `False`.", "title": "Is Convex", "type": "boolean" }, "is_twice_differentiable": { "default": false, "description": "Whether the function expression is twice differentiable or not. Defaults to `False`", "title": "Is Twice Differentiable", "type": "boolean" }, "scenario_keys": { "anyOf": [ { "items": { "type": "string" }, "type": "array" }, { "type": "null" } ], "default": null, "description": "Optional. The keys of the scenario the extra functions belongs to.", "title": "Scenario Keys" } }, "required": [ "name", "symbol" ], "title": "ExtraFunction", "type": "object" } ``` and an example of the JSON object corresponding to the schema looks like: **Click to expand** ``` { "name": "extra function example", "symbol": "e_f", "func": [ "Multiply", 5, "x" ], "simulator_path": null, "surrogates": null, "is_linear": true, "is_convex": true, "is_twice_differentiable": true, "scenario_keys": null } ``` ### ScalarizationFunction[¶](#scalarizationfunction) The `ScalarizationFunction` model defines any scalarizations of the problem being solved. The scalarization function has the fields `name`, `symbol` and `func`. The fields `name` and `symbol` represent the function's name and mathematical symbol. The `func` field is the mathematical representation of the scalarization function, it must be supplied either is the MathJSON format or "normal" infix notation. Usually, scalarization functions are added by various methods found in DESDEO, and are not expected to be supplied by users directly. Nevertheless, the field can be supplied by a user, if such a need arises. Its JSON schema of `ScalarizationFunction` looks as follows: **Click to expand** ``` { "description": "Model for scalarization of the problem.", "properties": { "name": { "description": "Name of the scalarization function.", "title": "Name", "type": "string" }, "symbol": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null, "description": "Optional symbol to represent the scalarization function. This may be used in UIs and visualizations.", "title": "Symbol" }, "func": { "description": "Function representation of the scalarization. This is a JSON object that can be parsed into a function.Must be a valid MathJSON object. The symbols in the function must match the symbols defined for objective/variable/constant/extra function.", "items": {}, "title": "Func", "type": "array" }, "is_linear": { "default": false, "description": "Whether the function expression is linear or not. Defaults to `False`.", "title": "Is Linear", "type": "boolean" }, "is_convex": { "default": false, "description": "Whether the function expression is convex or not (non-convex). Defaults to `False`.", "title": "Is Convex", "type": "boolean" }, "is_twice_differentiable": { "default": false, "description": "Whether the function expression is twice differentiable or not. Defaults to `False`", "title": "Is Twice Differentiable", "type": "boolean" }, "scenario_keys": { "default": null, "description": "Optional. The keys of the scenarios the scalarization function belongs to.", "items": { "type": "string" }, "title": "Scenario Keys", "type": "array" } }, "required": [ "name", "func" ], "title": "ScalarizationFunction", "type": "object" } ``` and an example of the JSON object corresponding to the schema looks like: **Click to expand** ``` { "name": "scalarization function example", "symbol": "s_f", "func": [ "Multiply", "x", "e_f" ], "is_linear": false, "is_convex": false, "is_twice_differentiable": false, "scenario_keys": null } ``` ### DiscreteRepresentation[¶](#discreterepresentation) The `DiscreteRepresentation` model defines a discrete representation of a problem. This representation is defined by the decision variable and objective function value pairs, which are defined in the fields `variable_values` and `objective_values`, respectively. This representation may consist of only non-dominated solutions, or it may contain dominated solutions as well. This is indicated by the `non_dominated` field. This representation is useful for problems that do not have an analytical formulation. It may also be used in conjunction with an analytical formulation. Some interactive multiobjective optimization methods can utilize both representations, while other are better suited just for one. For instance, NAUTILUS Navigator is best utilized with a discrete representation. The JSON schema `DiscreteRepresentation` looks as follows: **Click to expand** ``` { "description": "Model to represent discrete objective function and decision variable pairs.\n\nCan be used alongside an analytical representation as well.\n\nUsed with Objectives of type 'data_based' by default. Each of the decision\nvariable values and objective functions values are ordered in their\nrespective dict entries. This means that the decision variable values found\nat `variable_values['x_i'][j]` correspond to the objective function values\nfound at `objective_values['f_i'][j]` for all `i` and some `j`.", "properties": { "variable_values": { "additionalProperties": { "items": { "anyOf": [ { "type": "number" }, { "type": "integer" }, { "type": "boolean" } ] }, "type": "array" }, "description": "A dictionary with decision variable values. Each dict key points to a list of all the decision variable values available for the decision variable given in the key. The keys must match the 'symbols' defined for the decision variables.", "title": "Variable Values", "type": "object" }, "objective_values": { "additionalProperties": { "items": { "type": "number" }, "type": "array" }, "description": "A dictionary with objective function values. Each dict key points to a list of all the objective function values available for the objective function given in the key. The keys must match the 'symbols' defined for the objective functions.", "title": "Objective Values", "type": "object" }, "non_dominated": { "default": false, "description": "Indicates whether the representation consists of non-dominated points or not.If False, some method can employ non-dominated sorting, which might slow an interactive method down.", "title": "Non Dominated", "type": "boolean" } }, "required": [ "variable_values", "objective_values" ], "title": "DiscreteRepresentation", "type": "object" } ``` and an example of the JSON object corresponding to the schema looks like: **Click to expand** ``` { "variable_values": { "x": [ 1 ] }, "objective_values": { "f": [ 1.0 ] }, "non_dominated": false } ``` ## Symbols and expressions[¶](#symbols-and-expressions) The field `symbol`, which is found across the `Problem` schema, plays a very important role in DESDEO. It is utilized to identify variables, constants, and function expression. Symbols can also be utilized across the fields of `Problem` to refer to each other. In other words, the `func` field in a `ScalarizationModel` can contain the symbol referencing the `func` field of an `ExtraFunction`, or the value of a `Constant`, for instance. This is also an important fact to keep in mind when parsing the a `Problem` model from one representation to another. This will be discussed in more detail in the section [Parsing and Evaluating Problems](https://desdeo.readthedocs.io/en/latest/explanation/parsing_and_evaluating/#parsing-and-evaluating-problems). It is assumed that any expression in a `func` field, that is not a numerical value, refers to either a symbol or a mathematical operation. In what follows, the reserved symbols are presented in the section [Reserved symbols](#reserved-symbols). The supported mathematical expressions are presented in the section [Supported Operations](#supported-operations). ### Reserved symbols[¶](#reserved-symbols) In essence, any symbol that starts with an underscore, e.g., `_x` is considered to be reserved. This is because some of the routines in DESDEO that manipulate the problem formulation may add, for instance, auxiliary variables, which are automatically named with a symbol that starts with an underscore. To avoid confusion and bugs, users are advised to avoid utilizing symbols starting with underscores when defining problems. Another symbol, which is should be avoided, is any symbol that ends in `_min`, e.g., `f_1_min`. Since DESDEO internally transforms all expressions to be optimized into their minimization form, routines will append a `_min` to symbols to indicate that the expression the symbol represents, is to be, or has been, minimized. Other routines will expect these symbols to be available. Users are therefore advised to avoid symbols that end in a `_min`. ### Scalar and indexed expressions[¶](#scalar-and-indexed-expressions) DESDEO supports two kinds of expresssions: scalar and indexed ones. A scalar expression represents a single value or variable, while an indexed expression represents a collection of values or variables. For instance, an instance of the `Variable` or `Constant` model would represent a scalar expression, and an instance of the `TensorVariable` or `TensorConstant` would represent an indexed expression. Both scalar and indexed expression may be combined, such as taking the dot product of two indexed expressions representing vectors and adding a scalar to it. Some operators work only with scalar expressions, while others work with only indexed ones. Please refer to the table in the next section for further details on which operations support which type of expression. Note When modeling a problem that contains indexed expressions, it is important to choose a solver that supports indexed expressions. Please refer to the section [Summary of Solvers](https://desdeo.readthedocs.io/en/latest/explanation/solvers/#summary-of-solvers) for further details on which solvers support solving problems with indexed expressions and their operators. ### Supported Operations[¶](#supported-operations) Expressions representing mathematical operations are automatically identified by DESDEO. The expressions are case sensitive. Currently supported operations are listed in the table below: Note The equivalent infix notation operator is given in parentheses. For operators without this equivalent, the operator will still work in infix notation, e.g., `Sin(x) + 3`. | Expression | Explanation | Notes | | ------------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Negate (-) | Negates the value (changes its sign). | Element-wise for indexed expressions. Shapes must match. | | Add (+) | Adds two values. | Element-wise for indexed expressions. Shapes must match. | | Subtract (-) | Subtracts one value from another. | Element-wise for indexed expressions. Shapes must match. | | Multiply (\*) | Multiplies two values. | Element-wise for indexed expressions. Shapes must match. Indexed expression can be multiplied with a scalar where each indexed element is multiplied by the scalar's value. | | Divide (/) | Divides one value by another. | Not supported for indexed expressions (use Multiply) | | MatMul (@) | Matrix multiplication. | Matrix multiplication for indexed expressions. Does not support scalar expressions. | | Sum | Indexed component summation. | Sums the elements of an indexed expressions. Does not support scalar expressions. | | Exp | Calculates the exponential of a value. | Indexed expressions not supported. | | Ln | Natural logarithm of a value. | Indexed expressions not supported. | | Lb | Logarithm base 2 of a value. | Indexed expressions not supported. | | Lg | Logarithm base 10 of a value. | Indexed expressions not supported. | | LogOnePlus | Natural logarithm of (1 + value). | Indexed expressions not supported. | | Sqrt | Square root of a value. | Indexed expressions not supported. | | Square | Squares a value. | Indexed expressions not supported. | | Power (\*\*) | Raises a value to the power of another. | Indexed expressions not supported. | | Abs | Absolute value. | Indexed expressions not supported. | | Ceil | Rounds a value up to the nearest integer. | Indexed expressions not supported. | | Floor | Rounds a value down to the nearest integer. | Indexed expressions not supported. | | Arccos | Inverse cosine of a value. | Indexed expressions not supported. | | Arccosh | Inverse hyperbolic cosine of a value. | Indexed expressions not supported. | | Arcsin | Inverse sine of a value. | Indexed expressions not supported. | | Arcsinh | Inverse hyperbolic sine of a value. | Indexed expressions not supported. | | Arctan | Inverse tangent of a value. | Indexed expressions not supported. | | Arctanh | Inverse hyperbolic tangent of a value. | Indexed expressions not supported. | | Cos | Cosine of a value. | Indexed expressions not supported. | | Cosh | Hyperbolic cosine of a value. | Indexed expressions not supported. | | Sin | Sine of a value. | Indexed expressions not supported. | | Sinh | Hyperbolic sine of a value. | Indexed expressions not supported. | | Tan | Tangent of a value. | Indexed expressions not supported. | | Tanh | Hyperbolic tangent of a value. | Indexed expressions not supported. | | Max | Finds the maximum of values. | Indexed expressions not supported. | # Scalarization[¶](#scalarization) One approach to solve multiobjective optimization problems is to *scalarize* them. Scalarization transforms a multiobjective optimization problem into a single-objective optimization problem, which can be solved with one of the many existing optimizers. DESDEO has interfaces to existing optimizers, which are discussed in the section [Solvers](https://desdeo.readthedocs.io/en/latest/explanation/solvers). Here, we will first explain how scalarization is implemented in DESDEO in the section [Scalarizing problems](#scalarizing-problems), and we will then provide a couple of illustrative examples of scalarization in the section [Scalarization examples](#scalarization-examples). ## Scalarizing problems[¶](#scalarizing-problems) The core idea of scalarization in DESDEO is that scalarization functions are added to an existing [Problem][desdeo.problem.schema.Problem], and they are stored in its [scalarization_funcs][desdeo.problem.schema.Problem.scalarization_funcs] field. When a scalarization function is added to a problem, it does not modify the original problem, instead, functions that add scalarizations return always a copy of the problem with the added scalarization, and possibly other elements, such as constraints. When adding scalarization functions, it is very important to keep track of the added scalarization's [symbol][desdeo.problem.schema.ScalarizationFunction.symbol]. This is utilized, later on, in solver, and must be supplied to the solver so that it is aware of the function it should optimize. This is why the functions that add scalarizations return also the symbol that has been used when defining the [ScalarizationFunction][desdeo.problem.schema.ScalarizationFunction] that has been added to the problem. There is one last important note about scalarization functions. All scalarization functions are defines with the assumption that all of the objective functions, and elements related to the objective function values, e.g., the ideal and the nadir point, a possible reference point, have been defined such that the objective functions are to be minimized. This means that the scalarization function implementation will refer to objective functions with the `_min` post-fix. E.g., a scalarization function will refer to an objective function `f_1` as `f_1_min`. **It is the responsibility of the evaluators found in DESDEO to make sure that the reference to `f_1_min` is available at time of evaluation.** This naturally means that scalarizations should be added to a problem *before* they are evaluated and solved. Note Scalarization functions assume that each objective function is to be minimized. This should be reflected in any other values that depend on whether an objective is to be maximized or minimized, such as the ideal and nadir points, or a reference point! ## Scalarization examples[¶](#scalarization-examples) Here, we will showcase how adding scalarization function to a problem looks like in practice in DESDEO. ### The non-differentiable achievement scalarizing function[¶](#the-non-differentiable-achievement-scalarizing-function) To add the non-differentiable variant of the [achievement scalarizing function](https://desdeo.readthedocs.io/en/latest/tutorials/moo_primer/#def:asf), we invoke the following code: In \[1\]: Copied! ``` from desdeo.problem.testproblems import dtlz2 from desdeo.tools import add_asf_nondiff # a problem with the objectives 'f_1', 'f_2', and 'f_3' problem = dtlz2(n_objectives=3, n_variables=5) # a reference point with an aspiration level for each objective function reference_point = {"f_1": 0.5, "f_2": 0.4, "f_3": 0.3} problem_w_asf, target = add_asf_nondiff(problem, symbol="target", reference_point=reference_point) ``` from desdeo.problem.testproblems import dtlz2 from desdeo.tools import add_asf_nondiff # a problem with the objectives 'f_1', 'f_2', and 'f_3' problem = dtlz2(n_objectives=3, n_variables=5) # a reference point with an aspiration level for each objective function reference_point = {"f_1": 0.5, "f_2": 0.4, "f_3": 0.3} problem_w_asf, target = add_asf_nondiff(problem, symbol="target", reference_point=reference_point) In the above example, the DTLZ2 problem has three objective functions named `f_1, f_2`, and `f_3`. We have also provided a reference point for the sake of example. The pattern of providing a reference point as a `dict` is a recurring theme when supplying any information with elements that correspond to individual objective functions. As for the arguments passed to `add_asf_nondiff`, the first argument is the problem the scalarization should be added to, the second is the symbol given to the added scalarization function, and the reference point contains the aspiration levels to be used in the scalarization. The function then returns a copy of the original problem, `problem_w_asf` that contains now the added scalarization. It also returns the symbol of the added scalarization function, which in this case is just `target`. It is important to keep track of the symbol given to the scalarization function added, because it will be needed when solving the problem. For this reason, the symbol is returned as well, even though it may seem redundant. Naming the symbol of an added scalarization function to be the `target` is a good pattern to follow, since we often add just a single scalarization function to a problem, and then solve it. The name `target` reminds us that it is the function we wish to optimize once we have scalarized the problem. One last note on the example given. Here, we have utilized the *non-differentiable* variant of the achievement scalarizing function. This means that it will contain a `max` term, which is generally not differentiable. One should therefore exercise caution when utilizing the non-differentiable variant, because if the scalarized problem would otherwise be differentiable, we lose this property if we use a non-differentiable scalarization function. Warning When adding scalarization functions to problems, be mindful of the mathematical properties of the functions defined in the problem (e.g., the objective functions and constraints) and those of the scalarization function itself. Using an improper scalarization can lead to a scalarized problem that has lost some "nice" properties of the original problem, such as differentiability. ### The epsilon-constraints scalarization[¶](#the-epsilon-constraints-scalarization) As a more complicated example on how scalarizations might have to be added, consider the [epsilon-constraints scalarization](https://desdeo.readthedocs.io/en/latest/tutorials/moo_primer/#def:epsilon). Here, we have to also add constraint functions to the problem. Luckily, in practice, this is quite straight-forward, as illustrated below: In \[2\]: Copied! ``` from desdeo.tools import add_epsilon_constraints # the same problem as above, with the objectives 'f_1', 'f_2', and 'f_3' epsilons = {"f_1": 0.5, "f_2": 0.4, "f_3": 0.3} epsilon_symbols = {"f_1": "eps_1", "f_2": "eps_2", "f_3": "eps_3"} problem_w_eps, target, constraint_symbols = add_epsilon_constraints( problem, symbol="target", constraint_symbols=epsilon_symbols, objective_symbol="f_2", epsilons=epsilons ) ``` from desdeo.tools import add_epsilon_constraints # the same problem as above, with the objectives 'f_1', 'f_2', and 'f_3' epsilons = {"f_1": 0.5, "f_2": 0.4, "f_3": 0.3} epsilon_symbols = {"f_1": "eps_1", "f_2": "eps_2", "f_3": "eps_3"} problem_w_eps, target, constraint_symbols = add_epsilon_constraints( problem, symbol="target", constraint_symbols=epsilon_symbols, objective_symbol="f_2", epsilons=epsilons ) In the above code example, we have the same problem as before, but now we have also the epsilon bounds for each objective function in `epsilons`, and the symbols to be given to the added constraints in `epsilon_symbols` (the argument in `constraint_symbols` in `add_epsilon_constraint`). Since the bounds and constraint symbols are related to the objective functions, they have been given in a `dict` with the keys being the symbols of the respective objective functions. The objective function to be actually minimized in the epsilon-constraints scalarization is passed as `objective_symbol`, which in this case if `f_2`. Therefore, there will be no constraint for the objective `f_2`, and the entries with the key `f_2` in `epsilons` and `epsilon_symbols` will be ignored. The symbol of `f_2` will be now `target` since it is the objective of the scalarization. As for the return value of `add_epsilon_constraints`, the first value is a copy of the original problem with the added scalarization, the second value is the symbols of the scalarization objective, and the last one, `constraint_symbols`, are the symbols of the newly added constraints. In the case of the above example the would be `["eps_1", "eps_3"]`, because the objective of the scalarization, `f_2`, does not require a constraint. The epsilon constraint method, unlike the non-differentiable variant of the achievement scalarizing function, retains the differentiability and linearity of the objective functions. However, it does add constraints, which means a solver must be able to support constrained problems. As many things in life, adding scalarization functions comes with trade-offs. ## Where to go next?[¶](#where-to-go-next) You can study the available scalarization functions found in the [scalarization module](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#scalarization). If you are interested in how a scalarized problem can be solved, you can proceed to the section [Solvers](https://desdeo.readthedocs.io/en/latest/explanation/solvers). # Scalarization-based methods[¶](#scalarization-based-methods) In DESDEO, scalarization-based methods are implemented in a modular fashion. This means that no method is provided *per se*, but instead the different components required to build the method are provided. This idea is best illustrated by examples. ## Example: The achievement scalarizing function method[¶](#example-the-achievement-scalarizing-function-method) In the achievement scalarizing function (ASF) method, a scalarization function is solved iteratively with new preference information provided by a decision maker. The preference information consists in this case of a reference point containing aspiration levels. Suppose we have an instance of `Problem` defined as `problem`: In \[1\]: Copied! ``` from desdeo.problem.testproblems import dtlz2 # an instance of Problem with three objectives 'f_1', 'f_2', and 'f_3' problem = dtlz2(n_objectives=3, n_variables=5) ``` from desdeo.problem.testproblems import dtlz2 # an instance of Problem with three objectives 'f_1', 'f_2', and 'f_3' problem = dtlz2(n_objectives=3, n_variables=5) Now, to "implement" the ASF method, we first need preference information from the decision maker. Here, `reference_point` is a dictionary of aspiration levels, one for each objective function. In \[2\]: Copied! ``` # a reference point with an aspiration level for each objective function reference_point = {"f_1": 0.5, "f_2": 0.4, "f_3": 0.3} ``` # a reference point with an aspiration level for each objective function reference_point = {"f_1": 0.5, "f_2": 0.4, "f_3": 0.3} The ASF is defined as follows: $$ S\_\\text{AS}(F(\\mathbf{x}); \\mathbf{\\bar{z}}, \\mathbf{z}^\\star, \\mathbf{z}^\\text{nad}) = \\underset{i=1,\\ldots,k}{\\text{max}} \\left[ \\frac{f_i(\\mathbf{x}) - \\bar{z}\_i}{z^\\text{nad}\_i - (z_i^\\star - \\delta)} \\right] - \\rho\\sum\_{i=1}^{k} \\frac{f_i(\\mathbf{x})}{z_i^\\text{nad} - (z_i^\\star - \\delta)}, $$ where the variables (F(\\mathbf{x}) = [f_1(\\mathbf{x}),\\dots,f_k(\\mathbf{x})], \\mathbf{z}^\\star, \\mathbf{z}^\\text{nad}) are assumed to be available through the instance of `problem`. The variable (\\mathbf{\\bar{z}}) is our reference point, which is provided by a decision maker. Now, to create the ASF method, we add the ASF to the instance of `problem`. We use the differentiable variant `add_asf_diff` here: In \[3\]: Copied! ``` from desdeo.tools import add_asf_diff problem_w_asf, target = add_asf_diff(problem, symbol="s_asf", reference_point=reference_point) ``` from desdeo.tools import add_asf_diff problem_w_asf, target = add_asf_diff(problem, symbol="s_asf", reference_point=reference_point) In the above example, `add_asf_diff` creates an instance of the ASF where the variables of the function have been replaced by the corresponding variables found in the instance of `problem`. When adding scalarization functions of any type, at least the problem and a symbol must be supplied. In this example, the reference point is also needed. The symbol is important because it is used later in solvers to specify which scalarization function should be optimized. `add_asf_diff` returns a copy of the problem with the added scalarization (`problem_w_asf`) and the symbol of the added scalarization function (`target`), which here is `s_asf`. Note When adding scalarization functions of any kind, the returned symbol is very important because it is used to specify to solvers which scalarization function should be optimized. The symbol must be unique inside the instance of problem, i.e., no other field of a `problem` should share the same symbol. To solve the scalarized problem, we use a solver. For instance, `PyomoIpoptSolver` interfaces with the Ipopt solver. To solve the problem with it, we do: In \[4\]: Copied! ``` from desdeo.tools import PyomoIpoptSolver solver = PyomoIpoptSolver(problem_w_asf) result = solver.solve(target) ``` from desdeo.tools import PyomoIpoptSolver solver = PyomoIpoptSolver(problem_w_asf) result = solver.solve(target) As mentioned, the `target` symbol defined previously is now important so that we can tell the solver what to optimize when solving the scalarized problem. The solver returns a result object from which the optimal variables, objective values, and other information can be read. This iterative pattern, providing a reference point, scalarizing, and solving, is the basic building block of scalarization-based interactive methods in DESDEO. # Simulator and surrogate support in DESDEO[¶](#simulator-and-surrogate-support-in-desdeo) ## Simulator file[¶](#simulator-file) A `simulator file` connects an external simulator to DESDEO. It is a python script that is called from the [Evaluator][desdeo.problem.simulator_evaluator] with python's `subprocess.run` method. The evaluator passes to the simulator file decision variable values and whatever parameters the simulator may take. These parameters could be, for example, some variables the simulator needs that are not decision variables of the problem. The simulator file takes two arguments: - `-d`: a python dict of the decision variables as a list with each element representing a single sample, e.g., In \[1\]: Copied! ``` {"x_1": [1.5, 1.3, 1.4], "x_2": [-2.2, -2.0, -3.7], "x_3": [5.1, 10.7, 20.2]} ``` {"x_1": [1.5, 1.3, 1.4], "x_2": [-2.2, -2.0, -3.7], "x_3": [5.1, 10.7, 20.2]} Out\[1\]: ``` {'x_1': [1.5, 1.3, 1.4], 'x_2': [-2.2, -2.0, -3.7], 'x_3': [5.1, 10.7, 20.2]} ``` - `-p`: a python dict of the parameters, e.g., In \[2\]: Copied! ``` {"alpha": 10, "beta": -2} ``` {"alpha": 10, "beta": -2} Out\[2\]: ``` {'alpha': 10, 'beta': -2} ``` The simulator file returns the objective, constraint and extra function values as a python dict with the corresponding symbols as the keys of the dict and the corresponding values from the simulator as a list, with each element representing a single sample, as the dict's values. For example, In \[3\]: Copied! ``` { "f_1": [1.5, 5.4, 10.2], # an objective "f_2": [-2.2, 0.1, -5.3], # an objective "g_2": [-0.1, -0.2, 0.0], # a constraint "e_4": [10, 5.1, 2.1], # an extra function } ``` { "f_1": [1.5, 5.4, 10.2], # an objective "f_2": [-2.2, 0.1, -5.3], # an objective "g_2": [-0.1, -0.2, 0.0], # a constraint "e_4": [10, 5.1, 2.1], # an extra function } Out\[3\]: ``` {'f_1': [1.5, 5.4, 10.2], 'f_2': [-2.2, 0.1, -5.3], 'g_2': [-0.1, -0.2, 0.0], 'e_4': [10, 5.1, 2.1]} ``` The evaluator is then responsible for gathering those values and at the end, making sure that every objective, constraint and extra function is evaluated, whether they are analytical, simulator or surrogate based. ### An example of a simulator file[¶](#an-example-of-a-simulator-file) In what follows, an example of a simulator file is shown. The "simulator" used in the example is just a python function that takes the decision variables and parameters as arguments and returns something based on them. If needed the input arguments can be manipulated into a form the actual simulator can handle. First we need to import the necessary modules: ``` import argparse import ast import json import os import sys ``` The modules `argparse` and sys are used to identify and read the argumenets passed to the simulator file. The modules `ast` and `json` are used for parsing the arguments. For this example, a python function that runs the actual simulator: ``` import characters.fighter from combat import duel def simulator(variables: dict, parameters: dict) -> dict: """A function used to call the actual simulator.""" fighter = characters.fighter.L7_fighter() if parameters["rotation"] == "powerAttack": fighter.rotation = fighter.powerAttack_and_Strike fighter.AC = variables["AC"] fighter.AttackProficiency = variables["attack"] fighter.maxDamage = variables["damage"] fighter.maxCritDamage = fighter.maxDamage * 2 fighter.initiative = variables["initiative"] fighter._init_distributions() enemy = characters.fighter.L7_fighter() pWin, pLose = duel(fighter, enemy) return {"pWin": float(pWin[-1])} ``` The "simulator" takes the decision variables (`variables`) and parameters (`parameters`) as python dicts as arguments. It then does some computations with them and runs the simulator through the function `duel`. The simulator gives a value for the objective `pWin` that is then returned in a python dict. Now we need a script that parses the arguments passed from the evaluator into the correct form and calls the evaluator. Finally, the script passes the output dict from the simulator back to the evaluator via the `stdout` module. The evaluator then reads the stdout and the possible errors from the simulator file. The script looks something like ``` if __name__ == "__main__": # initialize the argument parser parser = argparse.ArgumentParser() # define help messages for when the arguments are missing vars_msg = ( "Variables for the simulator as a python dict. For example: {'x_1': [0, 1, 2, 3, 4], 'x_2': [4, 3, 2, 1, 0]}." ) params_msg = "Parameters for the simulator as a python dict. For example: {'alpha': 0.1, 'beta': 0.2}." # add the expected arguments parser.add_argument("-d", dest="vars", help=vars_msg) parser.add_argument("-p", dest="params", help=params_msg) # check that arguments are given, and if not, print out a message with information on the simulator file args = parser.parse_args(args=None if sys.argv[1:] else ["--help"]) # check that the expected arguments are given values, if not, print out a message with information on the missing argument if args.vars: # parse the argument from string form into a python dict using ast module's literal_eval method variables = ast.literal_eval(args.vars) else: parser.parse_args(["-h"]) if args.params: # parse the argument from string form into a python dict using ast module's literal_eval method parameters = ast.literal_eval(args.params) else: parser.parse_args(["-h"]) stdout = sys.stdout sys.stdout = open(os.devnull, "w") # call the simulator with the given variables and parameters simulator_output = simulator(variables, parameters) # send out the simulator outputs utilizing json.dumps method to keep the output as a dict to be parsed sys.stdout = stdout sys.stdout.write(json.dumps(simulator_output)) ``` In the script, we first initialize the argument parser and the expected arguments. Then we check that the arguments are given values and parse the values. Then the simulator itself is called with the arguments and the output of the simulator is gathered. Here the output of the simulator is in the correct form, a python dict, but if it was not, we would need to make the dict before sending it out. The output dict is then sent out via `sys.stdout.write` method and kept in the correct form by using `json.dumps` here and then `json.loads` in the evaluator end. # Solvers[¶](#solvers) While DESDEO is a framework for interactive multiobjective optimization, it does not implement any optimizers *per se*. Instead, DESDEO provides interfaces to many existing solvers. How these interfaces work in general is explained in the section [Solver interfaces](#solver-interfaces), while the currently implemented solvers in DESDEO are introduced and a couple of examples on how to use the solvers are given in the section [Solver examples](#solver-examples). ## Solver interfaces[¶](#solver-interfaces) The solver interfaces rely internally heavily on the evaluators discussed in the section [Parsing and evaluating](https://desdeo.readthedocs.io/en/latest/explanation/parsing_and_evaluating). It is the evaluators that make sure the `Problem` being solved is in a format that can be evaluated by a solver. The solver interfaces discussed here are in charge of making sure that when an outside solver evaluates a problem, the information from the solver is passed to the evaluator in a correct format, and that the output of the solver is then processed in a way that it can be utilized elsewhere in DESDEO. The interfaces also pass information from DESDEO to solvers in a compatible format. To put it simply, the solver interfaces are translators between the evaluators in DESDEO and the solvers found outside of DESDEO. ## Solver examples[¶](#solver-examples) How solvers can be utilized in practice is best illustrated with examples. We provide here a few examples on how to utilize different solvers through the solver interfaces available in DESDEO. We will use the Binh and Korn test problem throughout: In \[1\]: Copied! ``` from desdeo.problem.testproblems import binh_and_korn problem = binh_and_korn() ``` from desdeo.problem.testproblems import binh_and_korn problem = binh_and_korn() ### Scipy solvers[¶](#scipy-solvers) The Scipy solvers in DESDEO, found in the module [Scipy solver interfaces](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#scipy_solver_interfaces), can be used to interface with the optimization routines found in the Scipy library. There are interfaces to the solvers [`minimize`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) and [`differential_evolution`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.differential_evolution.html). Scipy solvers do not support TensorVariables. First, to illustrate the usage of the `minimize` interface, and the interfaces in general, consider the following example: In \[2\]: Copied! ``` from desdeo.tools import ScipyMinimizeSolver solver = ScipyMinimizeSolver(problem) results = solver.solve("f_1") results ``` from desdeo.tools import ScipyMinimizeSolver solver = ScipyMinimizeSolver(problem) results = solver.solve("f_1") results Out\[2\]: ``` SolverResults(optimal_variables={'x_1': 1.1510792319313623e-12, 'x_2': 7.140954494389007e-13}, optimal_objectives={'f_1': 7.339662836372162e-24, 'f_2': 49.99999999998135}, constraint_values={'g_1': -1.1510792319313623e-11, 'g_2': -65.29999999998587}, extra_func_values=None, scalarization_values=None, lagrange_multipliers=None, success=True, message='Optimization terminated successfully') ``` In the above example, we consider the Binh and Korn `Problem` with two objectives. We then create a solver by calling [`ScipyMinimizeSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.scipy_solver_interfaces.ScipyMinimizeSolver) and supplying it the problem we want to solve. This makes all the necessary setups for the solver and then returns an instance of the ScipyMinimizeSolver class, which we have stored in `solver`. To run the solver, we call the `solve` function with the symbol of the function defined in the problem we wish to minimize. Then, the solver returns a pydantic dataclass of type [`SolverResults`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.generics.SolverResults) with the results of the optimization. It is important to know that whichever function we request the solver to optimize, will be minimized. Therefore, in the example, if `f_1` was to be maximized instead, we should have called `solve` with the argument `f_1_min`. The results contained in SolverResults will then correspond to the original maximized function `f_1`. It is the jobs of the evaluators to make sure that `f_1_min` is available. Likewise, if we have [Scalarized](https://desdeo.readthedocs.io/en/latest/explanation/scalarization) the problem, we can give the solver the symbol of the added scalarization function. Likewise for [`ScipyDeSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.scipy_solver_interfaces.ScipyDeSolver) utilizing `differential_evolution`: In \[3\]: Copied! ``` from desdeo.tools import ScipyDeSolver solver = ScipyDeSolver(problem) results = solver.solve("f_1") results ``` from desdeo.tools import ScipyDeSolver solver = ScipyDeSolver(problem) results = solver.solve("f_1") results Out\[3\]: ``` SolverResults(optimal_variables={'x_1': 0.0, 'x_2': 0.0}, optimal_objectives={'f_1': 0.0, 'f_2': 50.0}, constraint_values={'g_1': 0.0, 'g_2': -65.3}, extra_func_values=None, scalarization_values=None, lagrange_multipliers=None, success=True, message='Optimization terminated successfully.') ``` Note Whichever function we request a solver to optimize, it will be minimized. ### Proximal solver[¶](#proximal-solver) The [`ProximalSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.proximal_solver.ProximalSolver) is useful when a `Problem` has been defined such that all of its objective functions have been defined with a [`DiscreteRepresentation`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.schema.DiscreteRepresentation). The proximal solver takes a symbol to optimize, and will return the decision variable values that correspond to the lowest value found for the symbol in the data. It works identically to the scipy solvers in the previous example: In \[4\]: Copied! ``` from desdeo.problem.testproblems import river_pollution_problem_discrete from desdeo.tools import ProximalSolver discrete_problem = river_pollution_problem_discrete() solver = ProximalSolver(discrete_problem) results = solver.solve("f1") results ``` from desdeo.problem.testproblems import river_pollution_problem_discrete from desdeo.tools import ProximalSolver discrete_problem = river_pollution_problem_discrete() solver = ProximalSolver(discrete_problem) results = solver.solve("f1") results Out\[4\]: ``` SolverResults(optimal_variables={'x_1': 0.3, 'x_2': 0.8583012325357192}, optimal_objectives={'f1': 4.751, 'f2': 3.0930520840181153, 'f3': 7.500000000000001, 'f4': -1.757091398096227, 'f5': 0.35000000000000003}, constraint_values=None, extra_func_values=None, scalarization_values=None, lagrange_multipliers=None, success=True, message="Optimal value found from tabular data minimizing the column 'f1'.") ``` ### Pyomo solvers[¶](#pyomo-solvers) The Pyomo solvers in DESDEO, found in the module [Pyomo solver interfaces](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#pyomo-solver-interfaces), use [Pyomo](https://pyomo.readthedocs.io/en/stable/) as a backend to interface with external optimization solvers. The [`PyomoEvaluator`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.pyomo_evaluator.PyomoEvaluator) transforms a `Problem` into a Pyomo `ConcreteModel`, which is then passed to the chosen external solver. Unlike the Scipy solvers, the Pyomo solvers support TensorVariables. There are four Pyomo-based solver interfaces: - **[`PyomoIpoptSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.pyomo_solver_interfaces.PyomoIpoptSolver)**: uses the [IPOPT](https://coin-or.github.io/Ipopt/) interior-point optimizer. Suitable for nonlinear, twice continuously differentiable problems (convex or non-convex). - **[`PyomoBonminSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.pyomo_solver_interfaces.PyomoBonminSolver)**: uses the [Bonmin](https://www.coin-or.org/Bonmin/) solver. Suitable for mixed-integer nonlinear problems requiring twice continuous differentiability. - **[`PyomoCBCSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.pyomo_solver_interfaces.PyomoCBCSolver)**: uses the [CBC](https://github.com/coin-or/Cbc) branch-and-cut solver. Suitable for linear and mixed-integer linear problems. - **[`PyomoGurobiSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.pyomo_solver_interfaces.PyomoGurobiSolver)**: uses [Gurobi](https://www.gurobi.com/) via the Pyomo interface. Suitable for mixed-integer linear and quadratic problems. The usage follows the same pattern as the Scipy solvers: In \[5\]: Copied! ``` from desdeo.tools import PyomoIpoptSolver solver = PyomoIpoptSolver(problem) results = solver.solve("f_1") results ``` from desdeo.tools import PyomoIpoptSolver solver = PyomoIpoptSolver(problem) results = solver.solve("f_1") results Out\[5\]: ``` SolverResults(optimal_variables={'x_1': 2.6242912620049366e-05, 'x_2': 1.7251689761471255e-05}, optimal_objectives={'f_1': 3.945245049638394e-09, 'f_2': 49.9995650549625}, constraint_values={'g_1': -0.00026242813988798855, 'g_2': -65.29968362452297}, extra_func_values=None, scalarization_values=None, lagrange_multipliers={'mu_g_1': -1.2372885782595755e-05, 'mu_g_2': -1.3912637951331793e-11}, success=True, message="Pyomo solver status is: 'ok', with termination condition: 'optimal'.") ``` Note The Pyomo solvers require the corresponding external solver binaries (e.g., `ipopt`, `bonmin`, `cbc`, or `gurobi`) to be installed and available on the system PATH. ### Gurobipy solver[¶](#gurobipy-solver) The [`GurobipySolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.gurobipy_solver_interfaces.GurobipySolver) is suitable for solving mixed-integer linear and quadratic optimization problems. GurobipySolver also does not support non-differentiable problems, for example, problems with some max terms, like many (non-differentiable) functions. Like the other solvers, the gurobipy solver takes the symbol of the objective function minimized (or maximized, with the above mentioned added `_min`) and returns the results of the optimization: In \[6\]: Copied! ``` from desdeo.problem.testproblems import simple_linear_test_problem from desdeo.tools import GurobipySolver linear_problem = simple_linear_test_problem() solver = GurobipySolver(linear_problem) results = solver.solve("f_1") results ``` from desdeo.problem.testproblems import simple_linear_test_problem from desdeo.tools import GurobipySolver linear_problem = simple_linear_test_problem() solver = GurobipySolver(linear_problem) results = solver.solve("f_1") results ``` Restricted license - for non-production use only - expires 2027-11-29 ``` Out\[6\]: ``` SolverResults(optimal_variables={'x_1': 4.199999999999999, 'x_2': 2.0999999999999996}, optimal_objectives={'f_1': 6.299999999999999}, constraint_values={'g_1': -0.0, 'g_2': -0.0}, extra_func_values=None, scalarization_values=None, lagrange_multipliers={}, success=True, message="Gurobipy solver status is: 'Optimal solution found.'") ``` ### Nevergrad solver[¶](#nevergrad-solver) The [`NevergradGenericSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.ng_solver_interfaces.NevergradGenericSolver) provides an interface to the gradient-free optimization platform [Nevergrad](https://facebookresearch.github.io/nevergrad/) (Facebook Research). It is useful when the problem is expensive to evaluate, non-differentiable, or otherwise unsuitable for gradient-based methods. Internally, the solver uses the [`SympyEvaluator`](https://desdeo.readthedocs.io/en/latest/api/desdeo_problem/#desdeo.problem.sympy_evaluator.SympyEvaluator), and therefore only supports scalar variables (no TensorVariables). The solver supports multiple optimizer choices, including NGOpt (default), CMA, PSO, TwoPointsDE, and others. It also supports parallel function evaluations via a thread pool by setting the `num_workers` option. In \[7\]: Copied! ``` import warnings from desdeo.tools import NevergradGenericSolver solver = NevergradGenericSolver(problem) with warnings.catch_warnings(): warnings.simplefilter("ignore") results = solver.solve("f_1") results ``` import warnings from desdeo.tools import NevergradGenericSolver solver = NevergradGenericSolver(problem) with warnings.catch_warnings(): warnings.simplefilter("ignore") results = solver.solve("f_1") results Out\[7\]: ``` SolverResults(optimal_variables={'x_1': 1.4142025106522738e-07, 'x_2': 3.0402165540621695e-07}, optimal_objectives={'f_1': 4.4971541746915384e-13, 'f_2': 49.999995545581044}, constraint_values={'g_1': -1.4142024014063281e-06, 'g_2': -65.29999956140603}, extra_func_values=None, scalarization_values=None, lagrange_multipliers=None, success=True, message='Recommendation found by NGOpt.') ``` ### Summary of Solvers[¶](#summary-of-solvers) The table below summarizes the solvers currently available in DESDEO. | Solver | Library | Problem type | Differentiability | Variables | License | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- | ----------------------------- | -------------------- | --------------- | ----------- | | [`ScipyMinimizeSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.scipy_solver_interfaces.ScipyMinimizeSolver) | SciPy | Nonlinear | Gradient-based | Scalar | Open-source | | [`ScipyDeSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.scipy_solver_interfaces.ScipyDeSolver) | SciPy | Nonlinear / black-box | Gradient-free | Scalar | Open-source | | [`ProximalSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.proximal_solver.ProximalSolver) | — | Discrete | Not required | Scalar | Open-source | | [`PyomoIpoptSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.pyomo_solver_interfaces.PyomoIpoptSolver) | Pyomo / IPOPT | Nonlinear | Twice differentiable | Scalar + Tensor | Open-source | | [`PyomoBonminSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.pyomo_solver_interfaces.PyomoBonminSolver) | Pyomo / Bonmin | Mixed-integer nonlinear | Twice differentiable | Scalar + Tensor | Open-source | | [`PyomoCBCSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.pyomo_solver_interfaces.PyomoCBCSolver) | Pyomo / CBC | Linear / mixed-integer linear | Not required | Scalar + Tensor | Open-source | | [`PyomoGurobiSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.pyomo_solver_interfaces.PyomoGurobiSolver) | Pyomo / Gurobi | Linear / quadratic | Not required | Scalar + Tensor | Commercial | | [`GurobipySolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.gurobipy_solver_interfaces.GurobipySolver) | Gurobipy | Linear / quadratic | Not required | Scalar + Tensor | Commercial | | [`PersistentGurobipySolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.gurobipy_solver_interfaces.PersistentGurobipySolver) | Gurobipy | Linear / quadratic | Not required | Scalar + Tensor | Commercial | | [`NevergradGenericSolver`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.ng_solver_interfaces.NevergradGenericSolver) | Nevergrad | Black-box | Gradient-free | Scalar | Open-source | # Evolutionary Algorithms in DESDEO[¶](#evolutionary-algorithms-in-desdeo) In this section, we will discuss how evolutionary algorithms (EAs) are implemented in DESDEO. As discussed in the [guide on EAs](https://desdeo.readthedocs.io/en/latest/howtoguides/ea), EAs are generally composed of modular components that can be reutilized in other EAs, or can be replaced with equivalent components. An EA can be seen as a pipeline of components that process the population of solutions in each generation. We first describe how DESDEO implements the components of an EA. Then, we describe how DESDEO supports the creation of such pipelines, and point out a few shortcomings with the approach regarding the flow of information between components. We then discuss how the Publish-Subscribe pattern can be used to improve the flow of information between components. Finally, we talk about the Pydantic interface that acts as a configuration/abstraction layer for the EA components and templates. ## EA Components[¶](#ea-components) In DESDEO, the components of an EA are implemented as classes with equivalent components sharing the same interface. As we will see later in Section [Publish-Subscribe Pattern](#publish-subscribe-pattern), all components are implemented as subclasses to the Subscriber class. However, for now, we will describe the structure of a typical EA component in a more general way. In general, an EA component has two main methods: 1. Component initializer: This method initializes the component with the necessary parameters. For example, the initializer of a crossover operator would take the probability of crossover as a parameter. The initializer should accept user provided hyperparameters and set the default values for the rest. The default `__init__` method of the class is used for this purpose. The function signature of the initializer of each component may be different (even for components of the same type). 1. Component execution: This method is called by the EA to execute the component. For example, the execution method of a crossover operator would take the current population and return a new population after applying the crossover operator. The function signature of each execution method must be the same for all components of the same type. However, the function signature may differ between components of different types. In general, the name of the execution method is also different for each component type, and can take an appropriate name that describes the function of the component. In addition to these two methods, a component may have other methods that are specific to the component. However, these other methods are not expected to be called by the EA, and are used internally by the component. For clarity, these may be marked as private methods by prefixing the method name with an underscore. ## Templates[¶](#templates) In DESDEO, the pipeline of an EA is created using templates. A template is simply a method that takes initialized components as arguments and runs their execution methods in a specific order. The order in which the components are executed is determined by the template itself. As each component of the same type is expected to have the same signature for the execution method, the template can call the execution method of each component without knowing the specifics of the component. For example, the template for a simple EA may look like this: In \[1\]: Copied! ``` from desdeo.emo.methods.templates import EMOResult from desdeo.emo.operators.crossover import BaseCrossover from desdeo.emo.operators.evaluator import EMOEvaluator from desdeo.emo.operators.generator import BaseGenerator from desdeo.emo.operators.mutation import BaseMutation from desdeo.emo.operators.selection import BaseSelector from desdeo.emo.operators.termination import BaseTerminator def template( generator: BaseGenerator, terminator: BaseTerminator, crossover: BaseCrossover, mutation: BaseMutation, evaluator: EMOEvaluator, selection: BaseSelector, ) -> EMOResult: """Implements a simple evolutionary algorithm template.""" solutions, outputs = generator.do() while not terminator.check(): offspring = crossover.do(population=solutions) offspring = mutation.do(offspring, solutions) offspring_outputs = evaluator.evaluate(offspring) solutions, outputs = selection.do(parents=(solutions, outputs), offsprings=(offspring, offspring_outputs)) return EMOResult(optimal_variables=solutions, optimal_outputs=outputs) ``` from desdeo.emo.methods.templates import EMOResult from desdeo.emo.operators.crossover import BaseCrossover from desdeo.emo.operators.evaluator import EMOEvaluator from desdeo.emo.operators.generator import BaseGenerator from desdeo.emo.operators.mutation import BaseMutation from desdeo.emo.operators.selection import BaseSelector from desdeo.emo.operators.termination import BaseTerminator def template( generator: BaseGenerator, terminator: BaseTerminator, crossover: BaseCrossover, mutation: BaseMutation, evaluator: EMOEvaluator, selection: BaseSelector, ) -> EMOResult: """Implements a simple evolutionary algorithm template.""" solutions, outputs = generator.do() while not terminator.check(): offspring = crossover.do(population=solutions) offspring = mutation.do(offspring, solutions) offspring_outputs = evaluator.evaluate(offspring) solutions, outputs = selection.do(parents=(solutions, outputs), offsprings=(offspring, offspring_outputs)) return EMOResult(optimal_variables=solutions, optimal_outputs=outputs) The template takes care of the general order in which the components are executed. Note that the template itself makes no assumptions about the exact nature of the components, or that of the problem. The same template can be used for continuous, discrete, or mixed-integer optimization problems, as long as the components are implemented correctly and they support the specific problem type. The initialization of the components is done outside the template, and this step can be used to make sure that the components actually support the problem at hand. The template also provides a basic pathway for the flow of information between components. In the example above, the outputs of the mutation operator are passed to the evaluator, and the outputs of the evaluator are passed to the selection operator. This is only possible because the components of the same type have the same signature for the execution method. However, this approach has a few shortcomings. In reality, different operators of the same kind may require different information. For example, there may be self-adaptive operators that take previous populations, or the expended budget of optimization as inputs. In general, it is not possible to predict the exact information that each operator may require. Changing the signature of the execution method of each component to accommodate all possible information is not a good idea, as it would make the components less modular, and the templates less reusable. In the next section, we discuss how the Publish-Subscribe pattern can be used to improve the flow of information between components. ## Publish-Subscribe Pattern[¶](#publish-subscribe-pattern) The [Publish-Suscribe pattern](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) is a messaging pattern where senders of messages (publishers) do not program the messages to be sent directly to specific receivers (subscribers). Instead, the publisher classifies the messages into classes without knowledge of who or how many subscribers, if any, there may be. Similarly, subscribers express interest in one or more classes and only receive messages that are of interest, without knowledge of which publishers, if any, there are. In the context of DESDEO, this means that each component can send messages to a central message broker, and subscribe to messages of interest. The message broker can then route the messages to the appropriate subscribers. This allows the components to be more modular, as they do not need to know the specifics of other components. The message broker can also be used to route messages to multiple subscribers, or to filter messages based on the content of the message. Essentially, the flow of information is decoupled from the templates, and the components can be more easily reused in different pipelines. There are a few differences between a generic Publish-Subscribe pattern and the implementation in DESDEO. In DESDEO, the components are implemented as subclasses of the [`Subscriber`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.patterns.Subscriber) class. Hence, even the components that are sending messages out are technically subscribers. There is a [`Publisher`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.patterns.Publisher) class as well. The `Publisher` class is the message broker mentioned in the previous paragraph. Each `Subscriber` can register itself to the `Publisher` and make sure that the `Publisher` knows which messages can be recieved from it. Furthermore, each `Subscriber` can also register topics that it is interested in. Once all components are registered, the `Publisher` can make sure that all topics that have been subscribed to are also being sent by one or more components. This way, the `Publisher` can make sure that all components are connected properly to each other. To enable this pattern, each component must be implemented as a `Subscriber` subclass. The `Subscriber` class enforces the impementation of the component to contain these four attributes/methods: 1. Attribute `provided_topics`: Is a dict that maps integers to a list of so called [`MessageTopics`](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#message-topics). The integer is the verbosity level for the component. A verbosity of zero forces the component to send no messages. A verbosity of one forces the component to send only information that are of type integer, float, bool, or string. A verbosity level of two additionally allows dictionaries, lists and polars dataframes. When an initialized component is registered to a Publisher, the `provided_topics` is used by the publisher to understand which topics the component can send messages about. 1. Attribute `interested_topics`: Is a list of `MessageTopics` that the component is interested in. When a component is registered to a Publisher, the `interested_topics` is used by the publisher to understand which topics the component is interested in. 1. Method `state`: This method is used to formulate the message that is sent by the component to the Publisher. The method should return a list of `Message` objects. The `Message` object is a simple Pydantic model that contains the message `topic`, the message `value`, as well as the message `source`, which is just the class name of the component (note, not the instance name). The `Subscriber` class provides a method named `notify`, which, when called, calls the `state` method and sends the messages to the Publisher. An appropriate time to call the `notify` method is at the end of the execution method of the component. 1. Method `update`: This method is used to receive messages from the Publisher. The method should accept a list of `Message` objects. Based on the content of the messages, the component can update its internal state. Note that the template itself does not need to be modified to accommodate the Publish-Subscribe pattern. In fact, the template does not invoke the publisher at all. Sending messages to the publisher (and therefore, the publisher sending the messages to other components) is done by interrupting the control flow of the template. However, the users of DESDEO, or even the developers of DESDEO do not need to worry about this as most of the heavy lifting is done by the Publisher and the Subscriber base classes. As long as the components are implemented correctly, with the information provided as stated above, the Publish-Subscribe pattern should work seamlessly. Note that another benefit of using the Publish-Subscribe pattern for the flow of information is that we are not limited to only using the components needed by the template. Additional components, such as archiving or visualization components can be registered to the publisher, and can receive messages from the other components. These components will work as expected even though the template itself does not invoke them. This allows for a more flexible and modular approach to implementing EAs in DESDEO. Below we provide an example of how the Publish-Subscribe pattern can be used to implement a simple EA. The example is a simplified implementation of the RVEA algorithm, which is a decomposition-based EA. The example is not complete, and is only meant to illustrate how the Publish-Subscribe pattern can be used to implement EAs in DESDEO. The complete implementation of RVEA can be found in the `rvea` method. The RVEA algorithm's selection operator needs to know how many generations have passed or how many evaluations have been made. This information is not available to the selection operator in the template. However, the selection operator can subscribe to messages about the number of generations or evaluations, and update its internal state accordingly. ``` # Create a Publisher object from desdeo.emo.methods.bases import template1 from desdeo.emo.operators.crossover import SimulatedBinaryCrossover from desdeo.emo.operators.generator import LHSGenerator from desdeo.emo.operators.mutation import BoundedPolynomialMutation from desdeo.emo.operators.selection import ReferenceVectorOptions, RVEASelector from desdeo.emo.operators.termination import MaxGenerationsTerminator from desdeo.tools.patterns import Publisher problem = Problem() publisher = Publisher() # Initialize the components, make sure that the components are passed the publisher object evaluator = EMOEvaluator( problem=problem, publisher=publisher, verbosity=2, ) reference_vector_options = ReferenceVectorOptions() selector = RVEASelector( problem=problem, publisher=publisher, reference_vector_options=reference_vector_options, verbosity=2, ) generator = LHSGenerator( problem=problem, evaluator=evaluator, publisher=publisher, verbosity=1, ) crossover = SimulatedBinaryCrossover( problem=problem, publisher=publisher, verbosity=1, ) mutation = BoundedPolynomialMutation( problem=problem, publisher=publisher, verbosity=1, ) n_generations = 10 terminator = MaxGenerationsTerminator(n_generations, publisher=publisher) # Each component above registered its provided topics with the publisher, and subscribed to # the topics it is interested in, as soon as it was constructed with that publisher. # Check whether all messages that have been subscribed to are also being sent by one or more components. Must be true. publisher.check_consistency() template1( evaluator=evaluator, crossover=crossover, mutation=mutation, generator=generator, selection=selector, terminator=terminator, ) ``` The `Publisher` class provides methods to register components and subscribe to topics. The `Publisher` class also provides a method to check the consistency of the messages being sent and received. Finally, the `Publisher` class provides a method named `relationship_map` that can be used to visualize the relationships between components. The `relationship_map` method generates a graph of the relationships between components, and can be used to debug the flow of information between components. Note that in the example above, only components that are needed by the template are registered to the publisher. Additional components can be registered to the publisher at any time, and can receive messages from the other components. While the above pattern makes it easy to implement new EAs and reuse components, it can also make it difficult to actually try out different configurations in an easy way. Alternatively, DESDEO provides complete implementations of some popular EAs, but they hide the internal workings and configuration options of the EA from the user. This issue is especially prominent when trying to do, e.g. hyperparameter tuning, or benchmarking of different algorithms. To solve this issue, DESDEO provides a Pydantic interface for the EA components and templates, which is discussed [here](https://desdeo.readthedocs.io/en/latest/explanation/pydantic_interface). # Test problems[¶](#test-problems) In DESDEO, some known test problem have been implemented and may be used to test the framework and the optimization methods implemented in it. Here, some of those test problems are introduced and described. ## The four bar truss design problem (RE21)[¶](#the-four-bar-truss-design-problem-re21) The four bar truss design problem [1] has, as its two objective functions, structural volume and joint displacement, and areas of member cross-sections as the four decision variables. The decision variables are constrained has four constraints related to member stresses. The variables are continuous and the problem's Pareto front is convex. The objective functions and constraints for the four bar truss design problem are defined as follows: $$\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = L(2x_1 + \\sqrt{2}x_2 + \\sqrt{x_3} + x_4) \\ & & f_2(\\mathbf{x}) & = \\frac{FL}{E}\\left(\\frac{2}{x_1} + \\frac{2\\sqrt{2}}{x_2} - \\frac{2\\sqrt{2}}{x_3} + \\frac{2}{x_4}\\right) \\ &\\text{s.t.,} & \\frac{F}{\\sigma} \\leq x_1 & \\leq 3\\frac{F}{\\sigma},\\ & & \\sqrt{2}\\frac{F}{\\sigma} \\leq x_2 & \\leq 3\\frac{F}{\\sigma},\\ & & \\sqrt{2}\\frac{F}{\\sigma} \\leq x_3 & \\leq 3\\frac{F}{\\sigma},\\ & & \\frac{F}{\\sigma} \\leq x_4 & \\leq 3\\frac{F}{\\sigma},\\ \\end{align}$$ where $x_1, x_4 \\in [a, 3a]$, $x_2, x_3 \\in [\\sqrt{2}a, 3a]$, and $a = F/\\sigma$. The parameters are defined as $F = 10$ $kN$, $E = 2e^5$ $kN/cm^2$, $L = 200$ $cm$, and $\\sigma = 10$ $kN/cm^2$. Here is an approximation of the four bar truss design problem's Pareto front: ## The reinforced concrete beam design problem (RE22)[¶](#the-reinforced-concrete-beam-design-problem-re22) In the reinforced concrete beam design problem [3], the first objective is to minimize the total cost of concrete and reinforcing steel of the beam. The second objective is to minimize the sum of the two constraint violations. The decision variable $x_1$ has a predefined discrete value[1](#foot_note_1) from 0.2 to 15. That makes the decision variables a mix of continuous and discrete variables. The objective functions and constraints for the reinforced concrete beam design problem are defined as follows: $$\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = 29.4x_1 + 0.6x_2x_3 \\ & & f_2(\\mathbf{x}) & = \\sum\_{i=1}^2 \\max{g_i(\\mathbf{x}), 0} \\ &\\text{s.t.,} & g_1(\\mathbf{x}) & = x_1x_3 - 7.735\\frac{x_1^2}{x_2} - 180 \\geq 0,\\ & & g_2(\\mathbf{x}) & = 4 - \\frac{x_3}{x_2} \\geq 0, \\end{align}$$ where $x_2 \\in [0,20]$ and $x_3 \\in [0,40].$ Here is an approximation of the reinforced concrete beam design problem's Pareto front: ## The pressure vessel design problem (RE23)[¶](#the-pressure-vessel-design-problem-re23) The pressure vessel design problem [4] involves a cylindrical pressure vessel that is capped at both ends by hemispherical heads. The first objective is to minimize the total cost, including the cost of material, forming and welding. The second objective is to minimize the sum of the three constraint violations. The decision variables $x_1$ and $x_2$ represent the thickness of the shell and the head, and the decision variables $x_3$ and $x_4$ represent the inner radius and length of the cylindrical section. The units for each decision variable are inches. The decision variables $x_1$ and $x_2$ are integer multiples of 0.0625 inches, which is the available thickness of rolled steel plates. That makes the decision variables a mix of continuous and discrete variables. The Pareto front for the problem is disconnected. The objective functions and constraints for the reinforced concrete beam design problem are defined as follows: $$\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = 0.6224x_1x_3x_4 + 1.7781x_2x_3^2 + 3.1661x_1^2x_4 + 19.84x_1^2x_3 \\ & & f_2(\\mathbf{x}) & = \\sum\_{i=1}^3 \\max{g_i(\\mathbf{x}), 0} \\ &\\text{s.t.,} & g_1(\\mathbf{x}) & = -x_1 + 0.0193x_3 \\leq 0,\\ & & g_2(\\mathbf{x}) & = -x_2 + 0.00954x_3 \\leq 0, \\ & & g_3(\\mathbf{x}) & = -\\pi x_3^2x_4 - \\frac{4}{3}\\pi x_3^3 + 1\\ 296\\ 000 \\leq 0. \\end{align}$$ Here is an approximation of the pressure vessel design problem's Pareto front: ## The hatch cover design problem (RE24)[¶](#the-hatch-cover-design-problem-re24) In the hatch cover design problem [3], the first objective is to minimize the weight of the hatch cover. The second objective is to minimize the sum of the four constraint violations. The two decision variables $x_1$ and $x_2$ represent the flange thickness and the beam height of the hatch cover. Both decision variables are continuous and the Pareto front for the problem is convex. The objective functions and constraints for the hatch cover design problem are defined as follows: $$\\begin{align} &\\min\_{\\mathbf{x}} & f_1(\\mathbf{x}) & = x_1 + 120x_2 \\ & & f_2(\\mathbf{x}) & = \\sum\_{i=1}^4 \\max{g_i(\\mathbf{x}), 0} \\ &\\text{s.t.,} & g_1(\\mathbf{x}) & = 1.0 - \\frac{\\sigma_b}{\\sigma\_{b,max}} \\geq 0,\\ & & g_2(\\mathbf{x}) & = 1.0 - \\frac{\\tau}{\\tau\_{max}} \\geq 0, \\ & & g_3(\\mathbf{x}) & = 1.0 - \\frac{\\delta}{\\delta\_{max}} \\geq 0, \\ & & g_4(\\mathbf{x}) & = 1.0 - \\frac{\\sigma_b}{\\sigma\_{k}} \\geq 0, \\end{align}$$ where $x_1 \\in [0.5, 4]$ and $x_2 \\in [4, 50]$. The parameters are defined as $\\sigma\_{b,max} = 700 kg/cm^2$, $\\tau\_{max} = 450 kg/cm$, $\\delta\_{max} = 1.5 cm$, $\\sigma_k = Ex_1^2/100 kg/cm^2$, $\\sigma_b = 4500/(x_1x_2) kg/cm^2$, $\\tau = 1800/x_2 kg/cm^2$, $\\delta = 56.2 \\times 10^4/(Ex_1x_2^2)$, and $E = 700\\ 000 kg/cm^2$. Here is an approximation of the hatch cover design problem's Pareto front: ## UTOPIA forest problem[¶](#utopia-forest-problem) The UTOPIA forest problem aims to find climate-smart solutions. It is a three-objective problem with the objectives representing the net present value, wood volume at the end of the planning period and the profit from harvesting. As seen in the following formulation, all these objectives are to be maximized. The UTOPIA forest problem is defined as follows: $$\\begin{align} \\max\_{\\mathbf{x}} & \\quad \\sum\_{j=1}^N\\sum\_{i \\in I_j} v\_{ij} x\_{ij} & \\ & \\quad \\sum\_{j=1}^N\\sum\_{i \\in I_j} w\_{ij} x\_{ij} & \\ & \\quad \\sum\_{j=1}^N\\sum\_{i \\in I_j} p\_{ij} x\_{ij} & \\ \\text{s.t.} & \\quad \\sum\\limits\_{i \\in I_j} x\_{ij} = 1, & \\forall j = 1 \\ldots N \\ & \\quad x\_{ij}\\in {0,1}& \\forall j = 1 \\ldots N, ~\\forall i\\in I_j, \\end{align}$$ where $x\_{ij}$ are decision variables representing the choice of implementing management plan $i$ in stand $j$, and $I_j$ is the set of available management plans for stand $j$. For each plan $i$ in stand $j$ the net present value, wood volume at the end of the planning period, and the profit from harvesting are represented by $v\_{ij}$, $w\_{ij}$, and $p\_{ij}$ respectively. ### Implementation[¶](#implementation) The implemented problem takes one compulsory argument `data` and two optional arguments, `holding` and `comparing`. The `data` argument is a list of strings that has the locations of (or paths to) the two data files used in the problem definition. In index 1 (as second element in the list) should be the "key" file. The second argument `holding` is an integer value representing the number of the holding in question and defaults to 1. The third argument `comparing` is a boolean value meant for testing purposes to compare the results gained with this implemetation to the ones from a previous implementation. This argument is therefore only relevant in testing the formulation and defaults to False. In the problem implementation, the decision variables are defined as vectors $\\mathbf{X}\_i$, where $i$ is the number of unique units in the holding in question, and the number of elements in each decision variable represents the number of unique management schedules in the holding. Each element in the decision variables is a binary, that can only have the values 0 or 1. As only one plan is ultimately chosen for each unit, only one element can have value 1 in each decision variable. A decision variable could look like this: `X_4 = [0, 0, 0, 1, 0]`, where the fourth management plan would be executed for the unit with index 4. ### Usage[¶](#usage) To use the UTOPIA forest problem, first you need to import and initialize the problem. In \[1\]: Copied! ``` from desdeo.problem.testproblems import forest_problem problem = forest_problem( simulation_results="../../tests/data/alternatives_290124.csv", treatment_key="../../tests/data/alternatives_key_290124.csv", holding=2, ) ``` from desdeo.problem.testproblems import forest_problem problem = forest_problem( simulation_results="../../tests/data/alternatives_290124.csv", treatment_key="../../tests/data/alternatives_key_290124.csv", holding=2, ) Above, we first import the problem and then initialize it for holding number 2. The data files in DESDEO are located in the `tests/data` directory. When using the UTOPIA forest problem, to see if it is used correctly, you can try optimizing one objective at a time and see whether the objective values match the ideal values of the objectives. The ideal values for each objective can be found in the problem definition and can be accessed in code as follows: In \[2\]: Copied! ``` # the forest problem does not have ideal defined ideal = problem.get_ideal_point() ``` # the forest problem does not have ideal defined ideal = problem.get_ideal_point() The above returns the ideal values as a python dict. For holding 2 the ideal would be In \[3\]: Copied! ``` ideal = {"f_1": 42937.004, "f_2": 2489.819, "f_3": 53632.887} ``` ideal = {"f_1": 42937.004, "f_2": 2489.819, "f_3": 53632.887} You can then test optimizing each objective separately by using one of the solvers in DESDEO (that supports tensors) and seeing if the results match each corresponding ideal value. If testing a new solver, replace `GurobipySolver` in the following example with the new solver. In \[4\]: Copied! ``` import numpy as np from desdeo.problem import objective_dict_to_numpy_array from desdeo.tools import GurobipySolver # you can replace this with any solver that supports tensors # initialize the solver solver = GurobipySolver(problem) # again, replace GurobipySolver with the solver being tested # optimize each objective separately f_1_results = solver.solve("f_1_min").optimal_objectives # always solve using _min f_2_results = solver.solve("f_2_min").optimal_objectives f_3_results = solver.solve("f_3_min").optimal_objectives # gather the results into an array results = [f_1_results["f_1"], f_2_results["f_2"], f_3_results["f_3"]] # turn the ideal dict into a numpy array for comparing purposes ideal_array = objective_dict_to_numpy_array(problem, ideal) # check that the results are close to the ideal values np.allclose(results, ideal_array) ``` import numpy as np from desdeo.problem import objective_dict_to_numpy_array from desdeo.tools import GurobipySolver # you can replace this with any solver that supports tensors # initialize the solver solver = GurobipySolver(problem) # again, replace GurobipySolver with the solver being tested # optimize each objective separately f_1_results = solver.solve("f_1_min").optimal_objectives # always solve using \\_min f_2_results = solver.solve("f_2_min").optimal_objectives f_3_results = solver.solve("f_3_min").optimal_objectives # gather the results into an array results = \[f_1_results["f_1"], f_2_results["f_2"], f_3_results["f_3"]\] # turn the ideal dict into a numpy array for comparing purposes ideal_array = objective_dict_to_numpy_array(problem, ideal) # check that the results are close to the ideal values np.allclose(results, ideal_array) ``` Restricted license - for non-production use only - expires 2027-11-29 ``` Out\[4\]: ``` True ``` If everything works, `np.allclose(results, ideal_array)` returns `True`. ## References[¶](#references) \[1\]: Cheng, F. Y., & Li, X. S. (1999). Generalized center method for multiobjective engineering optimization. Engineering Optimization, 31(5), 641-661. \[2\]: Tanabe, R. & Ishibuchi, H. (2020). An easy-to-use real-world multi-objective optimization problem suite. Applied soft computing, 89, 106078. . \[3\]: Amir, H. M., & Hasegawa, T. (1989). Nonlinear mixed-discrete structural optimization. Journal of Structural Engineering, 115(3), 626-646. \[4\]: Kannan, B. K., & Kramer, S. N. (1994). An augmented Lagrange multiplier based method for mixed integer discrete continuous optimization and its applications to mechanical design. 1. [^](#foot_cite_1) A set of predefined discrete values for the first decision variable: {0.2, 0.31, 0.4, 0.44, 0.6, 0.62, 0.79, 0.8, 0.88, 0.93, 1, 1.2, 1.24, 1.32, 1.4, 1.55, 1.58, 1.6, 1.76, 1.8, 1.86, 2, 2.17, 2.2, 2.37, 2.4, 2.48, 2.6, 2.64, 2.79, 2.8, 3, 3.08, 3, 1, 3.16, 3.41, 3.52, 3.6, 3.72, 3.95, 3.96, 4, 4.03, 4.2, 4.34, 4.4, 4.65, 4.74, 4.8, 4.84, 5, 5.28, 5.4, 5.53, 5.72, 6, 6.16, 6.32, 6.6, 7.11, 7.2, 7.8, 7.9, 8, 8.4, 8.69, 9, 9.48, 10.27, 11, 11.06, 11.85, 12, 13, 14, 15}. # Guides Guides are goal-oriented and are meant to direct users towards specific goals while utilizing DESDEO. ## General - **[Installing DESDEO](https://desdeo.readthedocs.io/en/latest/howtoguides/installing/index.md):** How to install DESDEO on your system ## Core-logic - **[Full worked example](https://desdeo.readthedocs.io/en/latest/howtoguides/full_example/index.md):** How to get started using modeling and solving problems - **[Defining problems in DESDEO](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_define_a_problem/index.md):** How to define a multiobjective optimization problem - **[Utilizing MCDM methods](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_utilize_mcdm_methods/index.md):** How to utilize 'MCDM' methods - **[NAUTILUS Navigator](https://desdeo.readthedocs.io/en/latest/howtoguides/nautilus_navigator/index.md):** How to use the NAUTILUS Navigator method - **[NAUTILI](https://desdeo.readthedocs.io/en/latest/howtoguides/nautili/index.md):** How to use the NAUTILI method - **[Using EAs in DESDEO](https://desdeo.readthedocs.io/en/latest/howtoguides/ea/index.md):** How to use evolutionary algorithms - **[Using EAs in DESDEO (Pydantic Interface)](https://desdeo.readthedocs.io/en/latest/howtoguides/ea_options/index.md):** How to use evolutionary algorithms with the Pydantic interface - **[Implementing new EA components](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_implement_ea/index.md):** How to implement new evolutionary algorithm components - **[Using the XLEMOO method](https://desdeo.readthedocs.io/en/latest/howtoguides/xlemoo/index.md):** How to use the explainable, learnable EMO (XLEMOO) method - **[Iterative Pareto Representer](https://desdeo.readthedocs.io/en/latest/howtoguides/IPR/index.md):** How to generate a representative set of solutions using the Iterative Pareto Representer - **[Using GDM SCORE bands](https://desdeo.readthedocs.io/en/latest/howtoguides/gdm_score/index.md):** How to use the group decision-making (GDM) SCORE bands method for consensus reaching - **[Advanced Usage of Surrogates](https://desdeo.readthedocs.io/en/latest/howtoguides/advancedSurrogates/index.md):** How to a combination of multiple surrogates and analytical objectives - **[Utilizing ADMs](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_use_adms/index.md):** Using artificial decision makers (ADMs) to compare EMO methods. ## Web-API and Web-GUI - **[Running the web-API and web-GUI](https://desdeo.readthedocs.io/en/latest/howtoguides/api_and_gui/index.md):** How to run the web-API and web-GUI - **[Solving problems with the web-GUI](https://desdeo.readthedocs.io/en/latest/howtoguides/webui_solving_problems/index.md):** How to locally set up a database and solve a problem using the web-GUI - **[Hosting on Kubernetes (old)](https://desdeo.readthedocs.io/en/latest/howtoguides/kubernetes/index.md):** How to host a DESDEO web application on Kubernetes - **[Deploying on OpenShift](https://desdeo.readthedocs.io/en/latest/howtoguides/deploying_on_openshift/index.md):** How to deploy DESDEO on OpenShift/Kubernetes (Rahti example) - **[Implementing method interfaces](https://desdeo.readthedocs.io/en/latest/howtoguides/implementing_method_interfaces/index.md):** How to implement new interactive method interfaces in the Web-GUI # Using the web-API and web-GUI Warning The web-API and web-GUI are currently under heavy development, so bugs and issues are expected to arise with their use. Be warned! Note This guide assumes that you have already [installed DESDEO](https://desdeo.readthedocs.io/en/latest/howtoguides/installing/index.md), and that you have created and activated a virtual environment. DESDEO's web-API is developed in Python and requires some extra dependencies, compared to the core-logic, to be installed. However, the web interface for DESDEO, the web-GUI, is developed in TypeScript, and requires its own packages and package manager for the dependencies to be installed. Below, instructions for setting up and running both the web-API and web-GUI are provided. ## Web-API ### Web-API prerequisites Install the `web` dependencies with the following command if you have not already done so: ``` uv sync ``` ``` poetry install ``` This will install the required dependencies for the web-API. The web-API itself is created with FastAPI and runs on Uvicorn. The source files for the web-API are located in the `desdeo/api` directory. ### Setting up the database The api needs a database to run, and the database connection is configured in the `desdeo/api/db.py` file. The default database connection is to a SQLite database (but can be changed to a more robust solution for production purposes, e.g., PostgreSQL). To generate the database schema, run the following command: ``` python desdeo/api/db_init.py ``` Once the database schema has been generated, you can start the web-API with the following command: ``` uvicorn --app-dir=./desdeo/api/ app:app --reload ``` ## Web-GUI ### Web-GUI prerequisites The source files for the web-GUI are located in the `webui` folder at the **root-level** of the project. Unlike the core-logic and the web-API, the web-GUI is developed in TypeScript. It is assumed that the node package manager `npm` ([link](https://www.npmjs.com/)) is available on the system. Use `npm` to install the web-GUI's dependencies ``` cd webui npm install ``` Note If errors arise related to an old or unsupported node version, the node version manager `nvm` ([link](https://github.com/nvm-sh/nvm)) can be used to select an appropriate version. ### Setting up the web-GUI There are some environmental variables that need to be defined before the web-GUI can be used in combination with the web-API and its database. Please refer to the [README](https://github.com/industrial-optimization-group/DESDEO/blob/master/webui/README.md) of the web-GUI for additional details. ### Running the web-GUI Assuming the web-API is setup and running correctly, the web-GUI should now be functional and can be hosted locally with the command ``` npm run dev -- --open ``` ## Script to automatically setting up and running the web-API and web-GUI At the root-level of the project, there is a script defined in the file `run_fullstack.sh`, which can be executed to easily setup and run both the web-API and web-GUI. However, the script does not install dependencies or set environmental variables, which must first still be configured manually as described above. After a successful setup, the web-API and web-GUI can be readily executed with one command: ``` python run_fullstack.py ``` There is also an equivalent `just` recipe: ``` just fullstack ``` If everything works as expected, we should now see debug output in our terminal for both the web-API and web-GUI, and the web-GUI should open in a new tab in your default browser. # How to deploy DESDEO on OpenShift (Kubernetes) ## Overview This guide walks through deploying the full DESDEO stack, FastAPI backend, SvelteKit web UI, and PostgreSQL database, on an OpenShift/OKD cluster. [CSC Rahti](https://rahti.csc.fi/) is used as the concrete example throughout; values specific to Rahti (hostnames, API endpoint, image registry URL) are marked so readers on other OpenShift clusters can substitute their own. Two approaches are documented: - **CLI approach**: uses YAML manifests and the `oc` CLI (command-line interface) exclusively. Every step is reproducible and version-controlled. The bulk of this guide follows this approach. - **Web console approach**: uses the Rahti web interface. Described under [Alternative web console approach](#web-console-approach) for users who prefer a graphical interface. OpenShift is a Kubernetes distribution with extra features layered on top. This guide uses OpenShift-specific objects (BuildConfig, ImageStream, Route) that do not exist in vanilla Kubernetes. If you are deploying on plain Kubernetes, consult your platform's documentation instead. The files you will work with live in two places in the DESDEO repository: - `deploy/`: all OpenShift manifests (ImageStreams, BuildConfigs, Deployments, StatefulSet, Routes, Job). - Several application-level files added or modified to support production deployment, described under [Repository preparation](#repository-preparation). ## Prerequisites - A CSC account with an active computing project. - Rahti access enabled for that project. Apply via [MyCSC](https://my.csc.fi) -> your project -> Services -> Rahti -> Apply for access. See [Rahti access](https://docs.csc.fi/cloud/rahti/access/) for details. - A Rahti project created in the [Rahti web console](https://console-openshift-console.apps.2.rahti.csc.fi/). When creating the project, include your CSC computing project number in the description field using the format `csc_project:#######`. - `oc` CLI installed (see [Using the Rahti CLI](https://docs.csc.fi/cloud/rahti/usage/cli/)). - Logged in to the cluster: ``` oc login https://api.2.rahti.csc.fi:6443 --token= ``` - Switched to your project: ``` oc project ``` - A fork or branch of the [DESDEO repository](https://github.com/industrial-optimization-group/DESDEO) with the `deploy/` files committed and pushed. Note Newly created CSC computing projects can take some time to become visible to Rahti. If project creation fails with an error, wait a few minutes and try again. ## Architecture Four components are deployed and wired together: 1. **`desdeo-api` Deployment**: FastAPI served by gunicorn+uvicorn, listening on port 8080. Built in-cluster using OpenShift's Source-to-Image (S2I) strategy from a custom Python builder image that includes COIN-OR solvers. 1. **`desdeo-webui` Deployment**: SvelteKit with adapter-node, listening on port 1. Built using the Docker strategy from `webui/Dockerfile`. All browser API calls are routed through a `/api/[...path]` proxy route baked into the SvelteKit app. This keeps cookies same-origin and avoids CORS complications. 1. **`desdeo-postgres` StatefulSet**: PostgreSQL running on the built-in OpenShift image, backed by a PersistentVolumeClaim. Alternatively, [CSC Pukki DBaaS](#option-b-pukki-dbaas) can be used instead. 1. **OpenShift Routes**: TLS-terminated at Rahti's HAProxy ingress. Certificates for `*.rahtiapp.fi` are provisioned automatically. ### URL environment variables Two env vars control how the API is reached, and they intentionally point to different targets: | Variable | Value | Used by | | -------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `VITE_API_URL` | `/api` | Baked into the client-side Javascript bundle at build time. Browser requests go to `/api/...`, which the SvelteKit proxy handles. | | `API_BASE_URL` | `http://desdeo-api:8080` | Set at runtime on the webui pod. SvelteKit's server-side proxy uses the internal cluster DNS name to reach the API, never exposed to the browser. | Warning Do not set `VITE_API_URL` to the API's external Route URL. The proxy architecture means the browser never talks directly to the API. Doing so causes cross-origin cookie issues that prevent authentication from working. ## Repository preparation The following files must be present in the repository before deploying. All manifests live under `deploy/`. | File | Purpose | | --------------------------------- | ------------------------------------------------------------------------- | | `deploy/secrets-template.yaml` | Template for creating credentials (never commit real values) | | `deploy/postgres.yaml` | StatefulSet, Service, and PVC for PostgreSQL | | `deploy/builder-imagestream.yaml` | ImageStream that tracks the custom S2I builder image | | `deploy/builder-buildconfig.yaml` | BuildConfig: Docker strategy, builds the solver-enabled S2I builder image | | `deploy/api-imagestream.yaml` | ImageStream that tracks built API images | | `deploy/webui-imagestream.yaml` | ImageStream that tracks built webui images | | `deploy/api-buildconfig.yaml` | BuildConfig: S2I using `desdeo-builder:latest`, GitHub webhook trigger | | `deploy/webui-buildconfig.yaml` | BuildConfig: Docker strategy, GitHub webhook trigger | | `deploy/api-deployment.yaml` | Deployment, Service, and Route for the API | | `deploy/webui-deployment.yaml` | Deployment, Service, and Route for the web UI | | `deploy/db-init-job.yaml` | One-shot Job that creates tables and seeds the initial user | In addition, several application-level files are required: - `.s2i/bin/assemble`: Custom S2I assemble script that uses `uv sync --frozen` to install Python dependencies. The default assemble script uses pip, which does not understand uv's `--group` flag. - `.s2i/environment`: Sets S2I environment variables such as `APP_MODULE`, `GUNICORN_CMD_ARGS`, and the port. - `desdeo/api/db_init_prod.py`: Production database initialisation script. The `db_init.py` debug branch does nothing in production mode; this separate script creates all SQLModel tables and seeds the initial analyst user. - `webui/Dockerfile`: Multi-stage Node 24 build. The `NPM_RUN=start:production` env var selects the adapter-node start script via `svelte.config.js`. - `webui/src/routes/api/[...path]/+server.ts`: The SvelteKit proxy route. It forwards all `/api/*` requests to the API using `event.fetch`, so the `handleFetch` hook in `hooks.server.ts` can intercept 401 responses and handle token refresh transparently. - `desdeo-s2i-buildimage.Dockerfile`: Builds the custom S2I builder image that extends the Python 3.12 UBI8 base with COIN-OR solvers (`bonmin`, `ipopt`, `cbc`). ## Step 1: Prepare secrets All credentials are stored in a Secret named `desdeo-secrets`. Two options are available, choose one and skip the other. Key reference of the stored secrets: | Key | Description | | ----------------------------------- | ---------------------------------------------------------------- | | `POSTGRES_USER` / `DB_USER` | PostgreSQL application user name | | `POSTGRES_PASSWORD` / `DB_PASSWORD` | Password for the above (same value) | | `DB_HOST` | Kubernetes Service name: `desdeo-postgres` (or Pukki hostname) | | `DB_PORT` | `5432` | | `DB_NAME` | Database name | | `AUTHJWT_SECRET` | JWT signing key, generate fresh, never reuse between deployments | | `DESDEO_ADMIN_USERNAME` | Initial analyst account username | | `DESDEO_ADMIN_PASSWORD` | Initial analyst account password | | `WEBHOOK_SECRET_API` | GitHub webhook secret for the API BuildConfig | | `WEBHOOK_SECRET_WEBUI` | GitHub webhook secret for the webui BuildConfig | Note `DESDEO_PRODUCTION=true` is set directly in the Deployment manifest, not as a Secret, because it is not sensitive. ### Options A: From `secrets.yaml` Copy the template, fill in the values, then apply it: ``` cp deploy/secrets-template.yaml deploy/secrets.yaml # Edit deploy/secrets.yaml, replace every accordingly oc apply -f deploy/secrets.yaml ``` Warning Make **absolutely sure** that the file `secrets.yaml` is **never** committed to git! ### Option B: From literals Create the secret and the two dedicated webhook secrets using `oc create secret generic`: ``` # Main application secret oc create secret generic desdeo-secrets \ --from-literal=POSTGRES_USER=desdeo \ --from-literal=POSTGRES_PASSWORD= \ --from-literal=DB_HOST=desdeo-postgres \ --from-literal=DB_PORT=5432 \ --from-literal=DB_NAME=desdeo \ --from-literal=DB_USER=desdeo \ --from-literal=DB_PASSWORD= \ --from-literal=AUTHJWT_SECRET=$(python3 -c "import secrets; print(secrets.token_hex(64))") \ --from-literal=DESDEO_ADMIN_USERNAME=admin \ --from-literal=DESDEO_ADMIN_PASSWORD= \ --from-literal=WEBHOOK_SECRET_API=$(python3 -c "import secrets; print(secrets.token_hex(24))") \ --from-literal=WEBHOOK_SECRET_WEBUI=$(python3 -c "import secrets; print(secrets.token_hex(24))") # Dedicated webhook secrets. OpenShift's secretReference requires the key # to be named exactly 'WebHookSecretKey'. Use the same values as above. oc create secret generic desdeo-webhook-api \ --from-literal=WebHookSecretKey= oc create secret generic desdeo-webhook-webui \ --from-literal=WebHookSecretKey= ``` ## Step 2: Deploy PostgreSQL Two options are available. Choose one and skip the other. ### Option A: In-cluster PostgreSQL (default) ``` oc apply -f deploy/postgres.yaml oc rollout status statefulset/desdeo-postgres ``` The StatefulSet uses the built-in Rahti PostgreSQL image. To check available tags on your cluster: ``` oc get is postgresql -n openshift -o jsonpath='{.spec.tags[*].name}' ``` Data is stored at `/var/lib/pgsql/data` in the PVC. Note The env vars that initialize the database are `POSTGRESQL_USER`, `POSTGRESQL_PASSWORD`, and `POSTGRESQL_DATABASE` (note the `POSTGRESQL_` prefix). The manifests map these from the Secret keys `POSTGRES_USER`, `POSTGRES_PASSWORD`, and the hardcoded value `desdeo`. ### Option B: Pukki DBaaS [Pukki](https://pukki.dbaas.csc.fi) is CSC's managed PostgreSQL service. It removes the need to deploy `deploy/postgres.yaml` entirely — skip that step if using Pukki. **Prerequisites**: add the Pukki service to your CSC computing project via MyCSC → your project → Services → Pukki → Apply for access. **Setup:** 1. Log in to [pukki.dbaas.csc.fi](https://pukki.dbaas.csc.fi). 1. Click **Launch Instance**. Give it a name. Default Volume Size, Datastore, and Flavor settings are fine for most deployments. 1. Under **Database Access**, add the Rahti egress IP: `86.50.229.150/32`. 1. Under **Initialize Databases**, create a database (e.g. `desdeo`) and set an admin username and password. These become `DB_USER`, `DB_PASSWORD`, and `DB_NAME` in the Secret. 1. Once the instance is running, copy the hostname from the Pukki dashboard. This becomes `DB_HOST` in the Secret instead of `desdeo-postgres`. Update the secret with the Pukki hostname: ``` oc create secret generic desdeo-secrets \ ... \ --from-literal=DB_HOST= \ ... ``` Skip `oc apply -f deploy/postgres.yaml`. All subsequent steps are identical regardless of which option you chose. Warning The Rahti egress IP `86.50.229.150/32` must be added to the Pukki access list before deploying. Without it the API pod cannot reach the database and will crash on startup. ## Step 3: Create ImageStreams and BuildConfigs An ImageStream is an OpenShift object that tracks versions of a container image. When a BuildConfig pushes a new image to an ImageStream, any Deployment watching that stream automatically triggers a rolling update, no external registry or CI system required. Apply the ImageStreams first: ``` oc apply -f deploy/builder-imagestream.yaml oc apply -f deploy/api-imagestream.yaml oc apply -f deploy/webui-imagestream.yaml ``` Before applying the BuildConfigs, open each file and substitute `` with the branch you want to build from (e.g. `master`). Ensure the git URI uses HTTPS, not SSH, because build pods do not have SSH credentials. The API BuildConfig uses the S2I strategy with `desdeo-builder:latest` as its builder image, the custom image built from `desdeo-s2i-buildimage.Dockerfile` that includes COIN-OR solvers. The webui BuildConfig uses the Docker strategy with `webui/Dockerfile`. The build arg `VITE_API_URL=/api` is passed explicitly. This is intentional, as browser requests go through the SvelteKit proxy rather than directly to the API. ``` oc apply -f deploy/builder-buildconfig.yaml oc apply -f deploy/api-buildconfig.yaml oc apply -f deploy/webui-buildconfig.yaml ``` ## Step 4: Trigger first builds The builder image must be ready before the API build can start, as `api-buildconfig.yaml` references `desdeo-builder:latest` as its S2I base. ``` # Build the solver-enabled builder image first (takes a few minutes). # --follow does not always work, Rahti's web-based interface can also be # used for monitoring progress. oc start-build desdeo-builder --follow # Then build the API and webui (can run in parallel once the builder is done) oc start-build desdeo-api --follow oc start-build desdeo-webui --follow ``` The first build takes longer than subsequent ones because there is no layer cache. Expect roughly a few minutes for the builder, and anther few minutes for both the API and the webui. Warning If the webui build fails with `exit status 137`, the build pod ran out of memory. Increase the build pod memory limit in `webui-buildconfig.yaml`: ``` spec: resources: limits: memory: 4Gi ``` Also ensure `NODE_OPTIONS=--max-old-space-size=3072` is set in `dockerStrategy.env`, then re-apply and re-trigger the build. ## Step 5: Deploy API and web UI ``` oc apply -f deploy/api-deployment.yaml oc apply -f deploy/webui-deployment.yaml oc rollout status deployment/desdeo-api oc rollout status deployment/desdeo-webui ``` Once the API pod is running, verify the solvers are present: ``` oc exec deployment/desdeo-api -- which bonmin ipopt cbc ``` All three should return paths under `/opt/solver_binaries/`. Warning Rahti enforces a maximum CPU limit-to-request ratio of 5:1. If `resources.limits.cpu` divided by `resources.requests.cpu` exceeds this, the ReplicaSet will silently fail to create pods. The error does not appear in pod logs, look in the ReplicaSet events: ``` oc describe replicaset ``` The manifests in `deploy/` are set within the allowed ratio. If you customize resource settings, check the ratio before applying. The following env vars must be present on the API pod at runtime: | Variable | Source | | --------------------------------------------------------- | ------------------------------------------------------------- | | `DESDEO_PRODUCTION` | Set to `true` directly in the Deployment manifest | | `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASSWORD` | From `desdeo-secrets` | | `AUTHJWT_SECRET` | From `desdeo-secrets` | | `CORS_ORIGINS` | Set in the Deployment to `["https://your-webui.rahtiapp.fi"]` | Note `COOKIE_DOMAIN` is intentionally not set. With the SvelteKit proxy architecture, cookies are owned by the webui host and forwarded server-side — the API does not need to set a shared cookie domain. ## Step 6: Initialize the database `db_init_prod.py` creates all SQLModel tables and seeds the initial analyst user defined by `DESDEO_ADMIN_USERNAME` and `DESDEO_ADMIN_PASSWORD`. It is safe to re-run — tables that already exist are not touched. Before applying, open `deploy/db-init-job.yaml` and replace `` with your Rahti project name. ``` oc apply -f deploy/db-init-job.yaml oc logs -f job/desdeo-db-init ``` Expected output: ``` [db-init] Tables ready. [db-init] Created user 'admin' (role=analyst, group=admin). [db-init] Done. ``` Once the job completes successfully, delete it: ``` oc delete job desdeo-db-init ``` Note Warnings about missing solvers (`bonmin`, `cbc`, `ipopt`) in the init job logs are harmless if the solver builder image has not been used. Once the API is rebuilt using `desdeo-builder:latest`, the warnings will disappear. ### Resetting the database To re-run the init job on an existing database (e.g. after adding new tables in a release), simply apply the job again. Existing data is not affected. To wipe the database entirely and start fresh, **all users, problems, and session data will be permanently deleted**: ``` # Drop and recreate the public schema oc exec -it statefulset/desdeo-postgres -- \ psql -U desdeo -d desdeo -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;" # Re-run the init job oc apply -f deploy/db-init-job.yaml oc logs -f job/desdeo-db-init oc delete job desdeo-db-init ``` Warning The schema drop is irreversible. All data will be permanently lost. ## Step 7: Verify ``` curl https://your-api.rahtiapp.fi/health # -> {"status":"ok"} curl -I https://your-webui.rahtiapp.fi/ # -> HTTP/2 200 # (a 307 redirect to /home is also normal) ``` Routes are TLS-terminated at Rahti's HAProxy ingress. Certificates for `*.rahtiapp.fi` are provisioned automatically, no manual certificate work is required. ## Step 8: Set up GitHub webhooks BuildConfigs include GitHub webhook triggers. Once configured, every push to the deploy branch triggers a rebuild of the affected component, which then rolls out automatically via the ImageStream trigger on the Deployment. Retrieve the webhook secret values from the dedicated webhook secrets: ``` oc get secret desdeo-webhook-api -o jsonpath='{.data.WebHookSecretKey}' | base64 -d oc get secret desdeo-webhook-webui -o jsonpath='{.data.WebHookSecretKey}' | base64 -d ``` Construct the webhook URLs: ``` https://api.2.rahti.csc.fi:6443/apis/build.openshift.io/v1/namespaces//buildconfigs/desdeo-api/webhooks//github https://api.2.rahti.csc.fi:6443/apis/build.openshift.io/v1/namespaces//buildconfigs/desdeo-webui/webhooks//github ``` In GitHub, go to your repository: **Settings -> Webhooks -> Add webhook** - Payload URL: the URL constructed above - Content type: `application/json`: required; `x-www-form-urlencoded` will be rejected - Secret: leave blank (the secret is embedded in the URL) - Events: Just the push event Add one webhook per BuildConfig. Note `oc describe bc/desdeo-api` always shows `` as a placeholder in the webhook URL, this is a display-only mask. Always retrieve the actual secret value from the Secret object as shown above. At this point, the desdei web-API and webui should be running on Rahti, and they should automatically update when new commits are pushed to the deployment branch. ## Troubleshooting | Symptom | Cause | Fix | | ----------------------------------------------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | API pod crashes with `ValidationError: authjwt_secret_key` | `AUTHJWT_SECRET` env var missing or key name wrong | Verify key names in the Secret match the Deployment's `secretKeyRef` fields | | API pod crashes with DB connection error | `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, or `DB_PASSWORD` missing or incorrect | Run `oc describe secret desdeo-secrets` and compare key names | | API pod crashes with connection timeout to Pukki | Rahti egress IP not whitelisted in Pukki access list | Add `86.50.229.150/32` to the Pukki instance's Database Access settings | | Webui pod never starts; `FailedCreate` in ReplicaSet events | CPU limit-to-request ratio exceeds 5:1 | Adjust `resources.requests.cpu` so that `limits.cpu / requests.cpu ≤ 5` | | Login returns 500; logs show `TypeError: Invalid URL` | `API_BASE_URL` env var not set on the webui pod | Set `API_BASE_URL=http://desdeo-api:8080` in the webui Deployment | | Build fails with `exit status 137` | Build pod out of memory | Set `spec.resources.limits.memory: 4Gi` in the BuildConfig | | Build fails with `pip install --group` error | Default S2I assemble script used instead of the custom one | Ensure `.s2i/bin/assemble` is present in the repo and uses `uv sync --frozen` | | `uv sync` fails with lockfile conflict | `uv.lock` is out of sync with `pyproject.toml` | Run `uv lock` locally and commit the updated lockfile | | Database init job fails with import errors | `DESDEO_PRODUCTION` not set; API falls back to SQLite mode | Ensure `DESDEO_PRODUCTION=true` is set in the Job env | | GitHub webhook returns 401 | Wrong content type or secret mismatch | Set content type to `application/json`; verify webhook secret matches `WebHookSecretKey` in the dedicated Secret | ## Known limitations - **Schema migrations**: `db_init_prod.py` uses `SQLModel.metadata.create_all`, which creates missing tables but does not ALTER existing ones. If the data model changes in a later release, tables must be migrated manually or via, e.g., Alembic, before redeploying. - **WebSocket connections**: The GDM-SCORE-bands and GNIMBUS features use `VITE_API_URL` directly for `ws://` connections and are not proxied through the SvelteKit `/api` route. These require separate handling not covered in this guide. ______________________________________________________________________ ## Web console approach The steps above use the `oc` CLI and YAML manifests. Rahti also provides a web console at [console-openshift-console.apps.2.rahti.csc.fi](https://console-openshift-console.apps.2.rahti.csc.fi/) that lets you accomplish the same tasks through a graphical interface. This section documents the web console approach as an alternative. Note The web console approach is less reproducible than the CLI approach and requires more manual steps on each redeployment. It is recommended for one-shot deploymnets or first-time exploration, not for ongoing deployments. ### Getting started Log in to the Rahti web console. Look for the **Create Project** button (you may need to switch to the Administrator perspective to see it). Fill in the project name and description. Include your CSC computing project number in the description in the format `csc_project:#######`. ### Deploying the API Navigate to **+Add -> Import from Git**. Enter the repository URL and branch under **Show advanced Git options -> Git reference**. Under **Build**, add the following environment variables: ``` DESDEO_PRODUCTION = true DB_HOST = DB_PORT = 5432 DB_NAME = desdeo DB_USER = DB_PASSWORD = AUTHJWT_SECRET = <64-char hex> CORS_ORIGINS = ["https://your-webui.rahtiapp.fi"] ``` The builder image should be set to `python:3.12-ubi9`. The S2I assemble script (`.s2i/bin/assemble`) uses `uv sync --frozen` to install dependencies. Store sensitive values in an OpenShift Secret and reference them in the Build configuration rather than entering them as plain text. ### Deploying the web UI Add another resource via **+Add -> Import from Git** using the same repository and branch. Under **Advanced Git Options**, set the **Context Dir** to `/webui`. Select **Docker build** as the build strategy (not S2I). The `webui/Dockerfile` handles the Node 24 build internally. Set these build arguments and environment variables: ``` VITE_API_URL = /api API_BASE_URL = http://:8080 ``` Warning Do not set `VITE_API_URL` to the API's public Route URL. Browser requests must go through the SvelteKit `/api` proxy, not directly to the API. If the build fails with `exit status 137`, increase the build memory limit in the BuildConfig YAML: ``` spec: resources: limits: memory: 4000Mi ``` ### PostgreSQL Use either Pukki DBaaS or a PostgreSQL image from the Rahti developer catalog. For Pukki, see [Option B: Pukki DBaaS](#option-b-pukki-dbaas) above, the setup steps are the same regardless of whether you use the CLI or web console. For in-cluster PostgreSQL, navigate to **+Add -> Developer Catalog** and find the PostgreSQL template. The correct env var names for the OpenShift image are `POSTGRESQL_USER`, `POSTGRESQL_PASSWORD`, and `POSTGRESQL_DATABASE`. ### Database initialization Once the API is running, use `db_init_prod.py` to create tables and seed the initial user. The recommended approach is to run it as a Kubernetes Job using the manifest in `deploy/db-init-job.yaml` (see [Step 6](#step-6-initialize-the-database)). Alternatively, you can exec into the API pod directly: ``` oc exec -it deployment/desdeo-api -- python desdeo/api/db_init_prod.py ``` # How to Implement Evolutionary Algorithm components in DESDEO Implementing evolutionary algorithm (EA) components though not difficult, is not a trivial task. Once you understand how to implement EA components in DESDEO, you will be able to create entirely new EAs or modify existing ones to better suit your optimization needs. Note that quite a few EA components are already implemented in DESDEO, so before implementing your own, check if an existing one fits your needs. This guide provides a step-by-step approach to implementing EA components in DESDEO. As a prerequisite, you should familiarize yourself with: - How multiobjective optimization problems are structured in DESDEO (see [here](https://desdeo.readthedocs.io/en/latest/explanation/problem_format/index.md)), - How evolutionary algorithms are structured in DESDEO (see [explanation](https://desdeo.readthedocs.io/en/latest/explanation/templates_and_pub_sub/index.md) and [usage](https://desdeo.readthedocs.io/en/latest/howtoguides/ea/index.md)), - How the Pydantic interface for EAs work (see [explanation](https://desdeo.readthedocs.io/en/latest/explanation/pydantic_interface/index.md) and [usage](https://desdeo.readthedocs.io/en/latest/howtoguides/ea_options/index.md)). Once you are familiar with these concepts, you can follow the steps below to implement your own EA components in DESDEO: 1. Implement the EA component as a Python method. 1. Classify the inputs of the method into three categories: initialization parameters, parameters that it can get from the template, and parameters that it will have to receive via the publisher-subscriber mechanism. 1. Implement a Python class that inherits from [Subscriber](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.patterns.Subscriber) as a wrapper for your method. 1. Implement a Pydantic model for your EA component to make sure it can be used through the Pydantic interface. 1. Test your implementation to ensure it works as expected. Let's implement a simple EA component as an example: an adaptive mutation operator that adjusts the mutation rate based on how long the optimization has been running. ## Step 1: Implement the EA component as a Python method The operator takes a population of offspring solutions as a NumPy array and applies mutation to each solution based on how many generations have passed relative to the maximum number of generations. The mutation rate decreases as the number of generations increases. The mutation is bound by specified minimum and maximum mutation values. ``` def adaptive_mutation( offspring: np.ndarray, generation: int, max_generations: int, base_mutation_rate: float, mut_min: float, mut_max: float ) -> np.ndarray: mutation_rate = base_mutation_rate * (1 - generation / max_generations) for i in range(offspring.shape[0]): if np.random.rand() < mutation_rate: mutation_value = np.random.normal(mut_min, mut_max, size=offspring.shape[1]) offspring[i] += mutation_value return offspring ``` Note The above implementation is just a simple example and not a suggestion for a practical mutation operator. Moreover, the implementation is not optimized for performance. Check NumPy's vectorized operations or Numba's JIT compilation for better performance in real-world applications. ## Step 2: Classify the inputs of the method The inputs of the `adaptive_mutation` method can be classified as follows: - Initialization parameters: `base_mutation_rate`, `mut_min`, `mut_max`. These are parameters that define the behavior of the mutation operator and are set when the operator is created. - Template parameters: To check whether an input parameter can be obtained from the template, check the implementation of the templates, or the implementation of existing EA components (in this case, other mutation operators). The source code for [`template1`](https://desdeo.readthedocs.io/en/latest/api/desdeo_emo/#desdeo.emo.methods.templates.template1) shows that mutation operators can only get the parent and offspring populations from the template. Therefore, in this case, `offspring` is a template parameter. However, the data is provided as a Polars DataFrame, so we will need to convert it to a NumPy array in the wrapper class. - Publisher-subscriber parameters: Any remaining parameters that are not initialization parameters or template parameters must be provided via the publisher-subscriber mechanism. In this case, `generation` and `max_generations` fall into this category. Note that as `max_generations` is a constant value throughout the optimization, it could also be considered as an initialization parameter. However, the Publisher-Subscriber mechanism provides this information, so we will use it from there. This reduces the number of parameters we need to set when creating the mutation operator. It also makes sure that we do not accidentally set a wrong value for `max_generations`. ## Step 3: Implement a Subscriber wrapper class Now that we have classified the inputs, we can implement a Subscriber wrapper class for the `adaptive_mutation` method. The class will inherit from [Subscriber](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#desdeo.tools.patterns.Subscriber). As stated [here](https://desdeo.readthedocs.io/en/latest/explanation/templates_and_pub_sub/#publish-subscribe-pattern), we need to implement four attributes/methods: 1. Attribute `provided_topics`: Topics for the publisher subscriber mechanism that the component will provide data for. 1. Attribute `interested_topics`: Topics for the publisher subscriber mechanism that the component needs data from. 1. Method `state`: A method that creates the messages to be sent to the `Publisher`. 1. Method `update`: A method that receives messages from the `Publisher` and performs updates the component. While implementing the class, make sure to follow the structure of other similar components in DESDEO. To check the available message topics and structures, check the [docs](https://desdeo.readthedocs.io/en/latest/api/desdeo_tools/#message-topics). ``` class AdaptiveMutation(Subscriber): @property def provided_topics(self) -> dict[int, Sequence[MutationMessageTopics]]: """The message topics provided by the mutation operator, grouped by verbosity level.""" return { 0: [], 1: [MutationMessageTopics.MUTATION_PROBABILITY], } @property def interested_topics(self): """The message topics that the mutation operator is interested in.""" return [TerminatorMessageTopics.GENERATION, TerminatorMessageTopics.MAX_GENERATIONS] def __init__( self, problem: Problem, base_mutation_rate: float, mut_min: float, mut_max: float, publisher: Publisher, verbosity: int, ): super().__init__(problem=problem, publisher=publisher, verbosity=verbosity) self.base_mutation_rate = base_mutation_rate # You can add checks to make sure that the initialization parameters are valid self.mut_min = mut_min self.mut_max = mut_max self.generation = None self.mutation_probability = None self.max_generations = None self.offsprings_original = None self.offsprings_mutated = None def do(self, offsprings: pl.DataFrame, parents: pl.DataFrame) -> pl.DataFrame: """Apply adaptive mutation to the offspring population.""" if self.generation is None or self.max_generations is None: raise ValueError("Generation and max_generations must be set before calling do method.") # Convert Polars DataFrame to NumPy array self.offsprings_original = copy(offsprings) offspring_array = offsprings.to_numpy() columns = offsprings.columns mutated_offspring_array = adaptive_mutation( offspring=offspring_array, generation=self.generation, max_generations=self.max_generations, base_mutation_rate=self.base_mutation_rate, mut_min=self.mut_min, mut_max=self.mut_max ) # Convert back to Polars DataFrame self.offsprings_mutated = pl.DataFrame(mutated_offspring_array, schema=columns) return self.offsprings_mutated def state(self) -> Sequence[Message]: """Return state messages.""" if self.verbosity == 0: return [] mutation_probability = self.base_mutation_rate * (1 - self.generation / self.max_generations) return [ FloatMessage( topic=MutationMessageTopics.MUTATION_PROBABILITY, source=self.__class__.__name__, value=mutation_probability, ), ] def update(self, message: Message) -> None: """Update the parameters for adaptive mutation. Args: message (Message): The message to update the parameters. The message should be coming from the Terminator operator (via the Publisher). """ if message.topic == TerminatorMessageTopics.GENERATION: self.generation = message.value if message.topic == TerminatorMessageTopics.MAX_GENERATIONS: self.max_generations = message.value return ``` ## Step 4: Implement a Pydantic model This is an optional step. You should be able to use the `AdaptiveMutation` operator without a Pydantic model by directly instantiating it and passing it to the EA template. However, if you want the operator to be usable through the Pydantic and want to make it available for others to use easily (including via the Web API), you need to implement a Pydantic model for it. This model needs to be implemented in `desdeo/emo/options/mutation.py`. It is a simple pydantic model that contains the initialization parameters for the mutation operator, along with a `name` attribute to identify the operator. It should also contain some sensible default values for the parameters. ``` class AdaptiveMutationOptions(BaseModel): """Pydantic model for AdaptiveMutation operator.""" name: Literal["AdaptiveMutation"] = "AdaptiveMutation" base_mutation_rate: float = Field( 0.1, description="Base mutation rate for the adaptive mutation operator.", gt=0, lt=1, ) mut_min: float = Field( 0.1, description="Minimum mutation value.", ge=0, lt=1, ) mut_max: float = Field( 0.5, description="Maximum mutation value.", ge=0, lt=1, ) ``` Finally, edit the `MutationOptions` union type to include the new model, and edit the `mutation_types` dictionary in the `mutation_constructor` method to include the new operator class. This can all be done in the same file (`desdeo/emo/options/mutation.py`). ## Step 5: Test your implementation After implementing the EA component, it is crucial to test it to ensure it works as expected. You can create unit tests that check the functionality of the `adaptive_mutation` method, the `AdaptiveMutation` class, and the Pydantic model. Test whether the new component works as intended by itself and when integrated into an EA template. # Implementing method interfaces in the Web-GUI This guide explains how to implement a new interactive method interface in DESDEO's Web-GUI. It covers the file structure, the separation between API handling and UI logic, and how to reuse existing components. This guide is meant as a general guideline, not as an absolute pattern. Prerequisites - A working API endpoint for the method (defined in `desdeo/api/routers/`). - The endpoint registered in the FastAPI app. - Orval-generated TypeScript types and endpoint functions (run `npm run generate:client` after adding API endpoints). ## File structure Each method lives in its own SvelteKit route directory: ``` webui/src/routes/interactive_methods// +page.ts # Data loader, fetches problems, passes to page handler.ts # API interaction layer, wraps orval endpoints +page.svelte # UI component, state, interaction, rendering +page.server.ts # (optional) Server-side auth guard types.ts # (optional) Method-specific TypeScript types helper-functions.ts # (optional) Pure utility functions ``` ### Why this structure? - `handler.ts` isolates all API calls. The page component never imports orval endpoints directly. - `+page.ts` runs before the page renders, loading data the component needs (e.g., the problem list). - `+page.svelte` focuses on state management and rendering, delegating API work to the handler. - `types.ts` and `helper-functions.ts` keep the main files focused. ## The handler pattern **Design principle: separate API handling from UI logic.** Each function in `handler.ts` wraps a single orval-generated endpoint. It calls the endpoint, checks the response status, and returns typed data or `null` on failure. The page component never sees raw HTTP responses. You should never have the need to manually specify URL's or endpoints; these should be handled through the Orval generated client. Otherwise, you might run into problems with user validation, for instance. ### Example: E-NAUTILUS handler ``` // handler.ts import type { ENautilusStepRequest, ENautilusStepResponse } from "$lib/gen/endpoints/DESDEOFastAPI"; import type { stepMethodEnautilusStepPostResponse } from "$lib/gen/endpoints/DESDEOFastAPI"; import { stepMethodEnautilusStepPost } from "$lib/gen/endpoints/DESDEOFastAPI"; export async function initialize_enautilus_state( request: ENautilusStepRequest ): Promise { const response: stepMethodEnautilusStepPostResponse = await stepMethodEnautilusStepPost(request); if (response.status != 200) { console.log("E-NAUTILUS init failed.", response.status); return null; } return response.data; } ``` Key points: - Typed inputs and outputs: the function signature documents what it expects and returns. - Status check: the handler decides what constitutes success, not the UI. - Returns `null` on failure: the page component checks for `null` and logs an error. ### Re-exporting shared handlers Methods often need session management. Rather than reimplementing it, re-export from the shared session handler: ``` // handler.ts or +page.svelte import { fetch_sessions, create_session } from '../../methods/sessions/handler'; export { fetch_sessions, create_session }; ``` ## The page loader (`+page.ts`) The loader fetches data before the page renders. Most methods need the problem list: ``` // +page.ts import type { PageLoad } from './$types'; import { getProblemsInfoProblemAllInfoGet } from '$lib/gen/endpoints/DESDEOFastAPI'; import type { ProblemInfo } from '$lib/gen/endpoints/DESDEOFastAPI'; type ProblemList = ProblemInfo[]; export const load: PageLoad = async () => { const res = await getProblemsInfoProblemAllInfoGet(); if (res.status !== 200) throw new Error('Failed to fetch problems'); return { problems: res.data satisfies ProblemList }; }; ``` ## Reusable components The Web-GUI provides several composable components that handle common UI patterns across all methods. These should be reused, when possible. ### Layout Every method page should use one of the layout components from `$lib/components/custom/method_layout/`: - `base-layout.svelte`: Simple flexbox layout with left sidebar, resizable center panes, and optional right sidebar. - `explainable-layout.svelte`: — Enhanced grid layout with sidebar state management. Use this for methods that need the advanced/explainable sidebar. Both layouts use Svelte 5 snippets for their slots: ``` {#snippet leftSidebar()} {/snippet} {#snippet visualizationArea()} {/snippet} {#snippet numericalValues()} {/snippet} ``` ### Preferences sidebar `$lib/components/custom/preferences-bar/preferences-sidebar.svelte` handles preference input for methods that use reference points, aspiration levels, or classifications. ``` ``` ### Visualizations panel `$lib/components/custom/visualizations-panel/visualizations-panel.svelte` renders parallel coordinate plots for comparing solutions. ``` ``` ### Solution table `$lib/components/custom/nimbus/solution-table.svelte` provides a data table with sorting, pagination, save/bookmark, and selection. ``` ``` ### Dialogs Reusable dialog utilities from `$lib/components/custom/dialogs/dialogs`: ``` import { openConfirmDialog, openInputDialog, openHelpDialog } from '$lib/components/custom/dialogs/dialogs'; // Confirmation before destructive action const confirmed = await openConfirmDialog("Revert to this iteration?", "This cannot be undone."); // Prompt for user input const name = await openInputDialog("Save solution", "Enter a name:"); ``` ## Putting it together The data flow through a method interface follows this pattern: ``` +page.ts (load problems) | v +page.svelte (receive data as props, manage state) | |--- user interacts (clicks iterate, selects solution, etc.) | | | v | handler.ts (call API, return typed data) | | | v |--- update state ($state variables) | | | v |--- components react (visualizations, tables, sidebars re-render) ``` ### Minimal skeleton **handler.ts:** ``` import { myMethodSolvePost } from "$lib/gen/endpoints/DESDEOFastAPI"; import type { MyMethodRequest, MyMethodResponse } from "$lib/gen/endpoints/DESDEOFastAPI"; export async function solve(request: MyMethodRequest): Promise { const response = await myMethodSolvePost(request); if (response.status !== 200) { console.error("Solve failed:", response.status); return null; } return response.data; } ``` **+page.ts:** ``` import type { PageLoad } from './$types'; import { getProblemsInfoProblemAllInfoGet } from '$lib/gen/endpoints/DESDEOFastAPI'; export const load: PageLoad = async () => { const res = await getProblemsInfoProblemAllInfoGet(); if (res.status !== 200) throw new Error('Failed to fetch problems'); return { problems: res.data }; }; ``` **+page.svelte:** ``` {#snippet leftSidebar()} {/snippet} {#snippet visualizationArea()} {#if problem && results} {/if} {/snippet} ``` # Installing DESDEO This guide goes over on how to install DESDEO on your machine and start utilizing it. ## Requirements DESDEO requires at least Python version `3.12`. Ensure this version is available on your system. ### Third party optimizers DESDEO relies on many 3rd party optimizers, we need to ensure that these are present on your system and available in the environment DESDEO is run. Currently, the external optimizers needed in DESDEO are: - Bonmin, - cbc, and - ipopt. These optimizers are part part of the [COIN-OR project](https://www.coin-or.org/). You may install these optimizers manually, or you can utilize pre-compiled binaries provided by the AMPL team [here](https://ampl.com/products/solvers/open-source-solvers/). You will need to register (which is free). Once registered, download the coin module for your system's architecture (Windows, Mac, or Linux). We also provide these same files in DESDEO's repository (under releases). To get specific binaries, use one of the following links: - [Windows](https://github.com/industrial-optimization-group/DESDEO/releases/download/supplementary/coin.mswin64.20230221.zip) - [Mac](https://github.com/industrial-optimization-group/DESDEO/releases/download/supplementary/coin.macos64.20211124.tgz) - [Linux (X86_64)](https://github.com/industrial-optimization-group/DESDEO/releases/download/supplementary/solver_binaries.tgz) After downloading the archive file with the solvers, ensure the contents of the unpacked directory (the binaries `bonmin`, `cbc`, and `ipopt`) are available in you system's `PATH` variable. It might be a wise idea to keep the binaries in the extracted folder in case they come with, e.g., shared libraries, which may depend on your architecture. ## Installation (general) Read first This section covers on how to install DESDEO using the source on GitHub. DESDEO is also available on PyPI to be installed via `pip`: ``` pip install desdeo ``` However, you may still required some of the [third party optimizers](#third-party-optimizers), and [setting up a virtual environment](#setting-up-a-virtual-environment) is never a bad idea. If you intend to install DESDEO from its current source on GitHub, read on! The following instructions assume you have (mostly) full control of your system. If you are installing DESDEO on a more restricted Windows environment, such as a work laptop, please see [this section](#installation-for-restricted-windows-pcs). ### Getting the source code To begin, use `git` (or download the source of DESDEO [here](https://github.com/industrial-optimization-group/DESDEO/)). If using `git`, you can get DESDEO's latest source code with the command (open a terminal or powershell): ``` git clone https://github.com/industrial-optimization-group/DESDEO ``` ### Setting up a virtual environment Before proceeding, we need to set up a virtual environment to run DESDEO and install its dependencies. Make sure you are at the root level of the DESDEO directory, which you should now have downloaded in your current working directory. E.g., in a terminal, `cd DESDEO`. To ensure you are in the correct directory, you should be able to see files like `pyproject.toml`, `README.md`, and others. There are many ways to setup and activate a virtual environment. We **recommend [`uv`](https://github.com/astral-sh/uv)**, which can manage Python versions, virtual environments, and dependencies in one tool, but several alternatives are shown below: This assumes you already have [`uv`](https://github.com/astral-sh/uv) available on your system. `uv` is handy, as it can be used to manage Python versions as well. To install Python 3.12 and create a virtual environment, run ``` uv venv --python 3.12 ``` This will download the latest version of Python 3.12 (if not already available) and then create a virtual environment in the current directory under a new folder `.venv`. If using the default virtual environment name `.venv`, `uv` will automatically use the virtual environment in subsequent invocations. Otherwise, the environment needs to be activated locally. ``` python -m venv .venv # (1)! ``` 1. Ensure that your Python's version is at least 3.12! To activate the environment: ``` source .venv/bin/activate ``` ``` .venv\Scripts\activate ``` ``` conda create --name .myenv python=3.12 ``` To activate the environment: ``` conda activate .myenv ``` Note Version 2.2 or greater of `poetry` is required! This assumes you already have [`poetry`](https://python-poetry.org/) available on your system. ``` poetry env activate # (1)! ``` 1. This assumes your system's Python version is 3.12. If not, you can use `poetry env use python3.12`, but this requires that version 3.12 is available on your system. **This command will print the command you must execute to activate the virtual environment. It does not activate it.** Copy-paste the command printed by poetry and execute it to activate the virtual environment. Note Remember to reactivate your virtual environment if you exit it, and then return to it. ### Installing dependencies After setting up a virtual environment, we next need to install DESDEO's dependencies. We **recommend using `uv`** for this. The `poetry` and `pip` options shown below also work, but `uv` is the tool used throughout DESDEO's development and CI. Make sure your virtual environment is activated! If not already done, we need to first install `uv`: ``` pip install uv ``` To install DESDEO's core-logic dependencies, run ``` uv sync --no-default-groups ``` If you wish to install the development and web dependencies as well, then run the following command instead: ``` uv sync ``` If not already done, we need to first install `poetry`: ``` pip install poetry # (1)! ``` 1. If `poetry` is already installed in your virtual environment, you may skip this step. After installing poetry, we can use the following command to install DESDEO's core-logic dependencies ``` poetry install --only main ``` If you wish to install the development and web dependencies as well, then run the following command instead: ``` poetry install ``` You can install desdeo and all optional dependencies by running ``` pip install -e . --group all-dev ``` If you don't want all the optional stuff, you can also specify different group(s) or no group at all. It's worth noting that pip does not automatically do anything to your virtual environments, so you will need to handle that manually. It also won't help you figure out conflicting dependencies. And now we should be done! DESDEO should now be available on your system in your current virtual environment. Extra dependencies? By default, `uv sync --no-default-groups` (or `poetry install --only main`) will install just the dependencies of the **core-logic**. This is meant for cases where DESDEO is used like a library, i.e., you do not intend to develop DESDEO or use the web-API or web-GUI parts of it. In case you wish to develop or utilize DESDEO past what the core-logic has to offer, then it is recommended to install all the extra dependencies. ## Installation (for restricted Windows PCs) This guide showcases how to install DESDEO specifically on a Windows machines, which might impose strict restrictions on what can be installed on the system, such as the work machines supplied by the University of Jyväskylä (JYU) using Anaconda. The steps outlined here should work on most Windows systems as long as you are using Anaconda for your Python installation. If you successfully installed DESDEO using the [general instructions](#installation-general), you do not need to read further. Note While this guide will refer to *JYU Windows machines*, it should be applicable to your restricted work machine regardless of company. However, if this is not the case, feel free to open an issue, and we will see what can be done. ### Anaconda First, install Anaconda. If you are on a JYU (or any other company's) Windows machine, you can get it from the Software Center (or equivalent) **without needing admin rights** for the installation. If not, please ask your IT support to install Anaconda on your machine. You can also download Anaconda from . If you prefer or have limited space available on your computer, [Miniconda](https://www.anaconda.com/docs/getting-started/miniconda/main) should work fine too. ### Installing DESDEO First, you need to open an Anaconda prompt. To find that, press the windows key and type `anaconda prompt`. #### Figure out the install location Next, you need to decide where on your computer you want to install DESDEO. If you are on a JYU Windows machine, I recommend something like `C:\MyTemp\code\DESDEO`. In your Anaconda prompt, type ``` mkdir C:\MyTemp\code ``` and ``` cd C:\MyTemp\code ``` That will create the desired folder and navigate there. Why I should not install DESDEO on my Desktop? On JYU Windows machines, your Desktop and Documents folders are not stored only on your hard drive, but on a network server. That can cause issues when running your own code, so you should store any code you write on your computer's hard disk. The `C:\MyTemp\` folder is a good place for that. #### Creating a virtual environment DESDEO requires at least Python version `3.12`. To control the version of Python we are using and what packages are available, we are first going to create a virtual environment, which we will name `desdeo`. In your Anaconda prompt, type ``` conda create -n desdeo python=3.12 ``` That will create a new virtual environment named desdeo that has Python 3.12 installed. You will probably be asked if you want to continue. You should probably answer yes. Then activate your new virtual environment by typing in your Anaconda prompt ``` conda activate desdeo ``` Why do I need a virtual environment? It is very common for your different programming projects to require different versions of Python and Python packages. By using virtual environments you do not have to uninstall and reinstall packages to get compatible versions, and you avoid *dependency hell*. You can just change the active virtual environment instead. #### Downloading DESDEO The best way to download DESDEO is to use git. If you do not know what git is or if you have it installed, type in your Anaconda prompt ``` git ``` If you get a response saying something like `'git' is not recognized as an internal or external command, operable program or batch file.`, then you likely do not have git installed. To install git, type in your Anaconda prompt ``` conda install git ``` and say yes when asked if you want to proceed. Once you have git installed, you can use it to download DESDEO. Type ``` git clone -b master --single-branch https://github.com/industrial-optimization-group/DESDEO.git ``` That creates a clone of the master branch of the DESDEO project. If you want all the branches, just use `git clone https://github.com/industrial-optimization-group/DESDEO.git`. Git should have created a new subfolder called DESDEO. Let us navigate there by typing ``` cd DESDEO ``` #### Installing dependencies After setting up a virtual environment and downloading the source code, we next need to install DESDEO's dependencies. Type in your Anaconda prompt ``` pip install -e . --group all-dev ``` If you don't want all the extras, you can list some other groups or no groups at all. #### Using uv with Anaconda You can also use uv if you want. Make sure you have it installed first (`pip install uv`). The default cache location for uv will likely not work on a JYU machine, because a normal user doesn't have the necessary rights there. Thus, you should change the default cache location of uv to, for example, the anaconda environment. ``` conda env config vars set UV_CACHE_DIR=%CONDA_PREFIX%\uv\cache VIRTUAL_ENV=%CONDA_PREFIX% UV_PROJECT_ENVIRONMENT=%CONDA_PREFIX% UV_PYTHON_INSTALL_DIR=%CONDA_PREFIX% UV_TOOL_DIR=%CONDA_PREFIX%\uv\tools conda activate desdeo ``` You can then use uv to install DESDEO and the required packages by typing ``` uv sync ``` ## Where to go next? To get a feel on how DESDEO can be utilized to model and solve multiobjective optimization problems in practice, checkout [this guide](https://desdeo.readthedocs.io/en/latest/howtoguides/full_example/index.md). # How to host a DESDEO web application on Kubernetes This is a how-to guide to setting up a DESDEO web application on Kubernetes. Specifically, the aim is to provide one easy way to get desdeo-webapi, desdeo-webui and a database running on [CSC Rahti](https://docs.csc.fi/cloud/rahti2/). Rahti is running Openshift OKD v4 with Kubernetes v1.28. If you are trying to host your web application somewhere else, all the steps presented here might not be directly applicable, but the process should be similar. ## Getting started on Rahti The first thing to do, is to create a project for your web application. To be able to do that on Rahti, you will first need CSC computing project to associate it with. See the [Rahti documentation](https://docs.csc.fi/cloud/rahti2/access/) on how to create one. The next step is to login to the [Rahti web interface](https://console-openshift-console.apps.2.rahti.csc.fi/). Once you are in, look for a `create project` button. You will likely need to be in the administrator role to see it. Input the name of the of the project, add a display name if you want one, and add a description. In Rahti the name of the project is kind of important, because it will appear as a part of all the automatically generated URLs pointing to your web application, so you will want to choose something short and to the point. In the description you will need to include the Project Number of your CSC computing project in format `csc_project:1234567`. Note It will take some time for the Rahti system to become aware of newly created computing projects. If you just created a new computing project and are getting an error when creating a Rahti project, just wait and it should sort itself out. Once you have your project set up, you can start adding resources to your project. ## DESDEO webapi To add a new resource i.e. piece of your web application, navigate to the `+Add` page. There, you want to choose `Import from Git` option. First, you will need to input a Github address to the repository that contains your DESDEO webapi code, for example `https://github.com/industrial-optimization-group/DESDEO`. You are unlikely to be using the main branch of the Git for your deployment, so click `Show advanced Git options` and add the name of your desired branch under `Git reference`. You probably don't need to touch any of the other advanced options. At this point, the system should have automatically figured out that you want to host a Python application and chosen you an appropriate `Builder Image version`. But if not, you can set it up manually. Note At the time of writing this, Rahti does not support Python versions newer than 3.9, and DESDEO2 uses Python 3.12. If you need to use a builder image that is not available on Rahti or need to customize the build image to add support for different solvers, for example, just use Python 3.9 to create the build configuration, and then change it later to use a [different build image](#adding-a-custom-build-image). Under the **General** section, you can choose the name of your application, which does not matter much, because it will not be visible outside the administrative interface, and the `Name` of your application component, which is kind of important, because it will be part of any URL pointing to that component. For the webapi it does not matter too much what you choose, but put some thought into what you name the webui, because your users are connecting to that part and can see the name. Under **Build** section you may want to adjust the advanced Build options, because that is the place to set up Environment variables that are present both during the build and while the application is running. This is a good way to tell your DESDEO webapi, for example, where to find the database it is supposed to connect to. You can either list the environment variables directly here or use a secret on Kubernetes. DESDEO2 uses the following Environment variables to get information about the database and the webui: ``` POSTGRES_USER # This is the username for the database POSTGRES_PASSWORD # This is the password for the database POSTGRES_HOST # This is the host of the database POSTGRES_PORT # This is the port used by the host POSTGRES_DB # This is the name of the database CORS_ORIGINS # This is a list of potential URLs where the webui might be hosted COOKIE_DOMAIN # Shared domain ending, from which cookies should be considered valid (for example, .2.rahtiapp.fi) AUTHJWT_SECRET # Secret key for jwt authentication. You will need to generate this yourself. ``` The `CORS_ORIGINS` variable is used to list the web sites for [Cross-origin resource sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing). It should list all the URLs where you might want to host your frontend. It should be in the format of a list of JSON string. For example, the default value if the environment variable is not set is `["http://localhost", "http://localhost:8080", "http://localhost:5173"]` You can also define other environment variables here or in your [S2I](#source-to-image-s2i) scripts. Your S2I scripts are not suited for storing sensitive information like database usernames and passwords, because they are typically uploaded on Github with your code. You will likely not need to touch anything under **Deploy** or **Advanced Options** for now. When you are done with your adjustments, click `Create` and the system will attempt to download your source code from the specified location, build a docker image, and finally run it. ## Source to image (S2I) The way Rahti transforms the code on Github to a web application is by using [Source-to-Image (S2I)](https://github.com/openshift/source-to-image) toolkit. You probably don't need to be familiar with its more intricate workings, but there is a lot of documentation and examples available online if you need it. To put simply, what S2I does is it 1. bundles up your code excluding the files defined in `.s2iignore` file, 1. sets the environment variables from `.s2i/environment`, 1. starts a container and runs the `assemble` script and waits for it to finish, 1. commits the container, setting the CMD for the output image to be the `run` script and tagging the image with the name provided. You can modify how S2I builds and runs your code by changing these scripts. DESDEO2 uses a custom `assemble` script for installing all the necessary dependencies and the default `run` script. It is unlikely you need to change these. You can do most of the necessary adjustments through the [environment variables used by s2i-python-container](https://github.com/sclorg/s2i-python-container/blob/master/3.9/README.md#environment-variables). Below is an example of `.s2i/environment` file used to run the current version of desdeo-webapi at thime of writing this guide ``` UPGRADE_PIP_TO_LATEST=1 APP_MODULE=desdeo.api.app:app GUNICORN_CMD_ARGS=--bind=0.0.0.0:8080 --workers=2 --access-logfile=- --worker-class uvicorn.workers.UvicornWorker DESDEO_INSTALL=. --group web --group server DEBUG=false ``` The first line tells that `pip` should be upgraded to the latest version. `APP_MODULE` denotes the app that [gunicorn](https://docs.gunicorn.org/) should run. `GUNICORN_CMD_ARGS` lists the other arguments given to gunicorn i.e. the server should be run for all ip addresses at port 8080, the number of workers should be 2 (the default is way too many), the logs should go to stdout, and most importantly, the workers-class should use uvicorn workers. The end result here is that the code in app:app will be run on a Gunicorn ASGI server using the given arguments. `DESDEO_INSTALL` is used to give additional parameters in the `pip install $DESDEO_INSTALL` command in the `asseble` script. `DESDEO_PRODUCTION` is present so that the API knows to use the correct configurations. [Desdeo-webui](#desdeo-webui) has custom `assemble` and `run` scripts included. This is because [s2i-nodejs-container](https://github.com/sclorg/s2i-nodejs-container/blob/master/18/README.md) does not include as many configuration options through environment variables. The custom scripts are not very complicated however. If you need to change them, the `assemble` and `run` scripts are found in the `webui/.s2i/bin/` folder. ## Adding a custom build image At the time of writing this, building DESDEO2 webapi will fail on Rahti, because Python version 3.12 is not available. To get around this, you will need a custom build image. If you just want something that supports Python 3.12, you can for example use `ubi8/python-312` Docker image from `registry.access.redhat.com/ubi8/python-312`. To tell Rahti to use this image to build, you need to go to your build config, which you can find, for example, on the right hand side of the screen when you have selected the app. Then you need to navigate to the **YAML** section and find the `spec.strategy.sourceStrategy`, which should have defaulted to what you see below if you created your app as a Python 3.9 application. You will want to update your `sourceStrategy` to ``` sourceStrategy: from: kind: DockerImage name: registry.access.redhat.com/ubi8/python-312 ``` ### Creating your own image However, if you also need your build image to do something extra, like installing additional solvers, you need to create your own build image. To be able to do this, you will need to install [Docker](https://www.docker.com/) (and you might find use for [openshift client](https://console-openshift-console.apps.2.rahti.csc.fi/command-line-tools)). If you just want to add the COIN-OR solvers and/or Gurobipy licence, you can use the `desdeo-s2i-buildimage.Dockerfile` found in the root of DESDEO2 branch. You can also use that file as an example and create your own dockerfile that does exactly what you need, or you can modify it. How to do that is beyond this guide. Ask your favorite AI assistant for help. To build an image from your dockerfile, use ``` docker build -t build-image -f desdeo-s2i-buildimage.Dockerfile . ``` You will then need to push that image somewhere Rahti can access it. I recommend using Rahti's image registry. Here's a [guide](https://docs.csc.fi/cloud/rahti2/images/Using_Rahti_2_integrated_registry/) on how to do that. Once your builder image is in Rahti's image registry, you can use the image in your `sourceStrategy` ``` sourceStrategy: from: kind: ImageStreamTag name: 'build-image:latest' ``` ## DESDEO webui The process of adding DESDEO webui to Rahti is very similar to the one detailed above with [DESDEO webapi](#desdeo-webapi), as long as you have done all the necessary preparations [relating to S2I](#source-to-image-s2i). First you go to the `+Add` page, then you choose `Import from Git` option. You add your Github link and write the correct branch under Advanced Git options. Because the webui is now found in the same repository as the rest of DESDEO, the system will not automatically figure out you are adding a Node application. You can switch to node application manually. You will also need add context dir `/webui` under advanced Git options. At the moment, Rahti has not added a build image for node 22, which is what DESDEO uses. That means you will need to set the build image manually. Webui does not need to do anything special with its build image, so you can just use the image from, for example, `registry.access.redhat.com/ubi9/nodejs-22:latest`. Under **General** you can choose your Application, which does not matter much, but you might want to use the same one as for the webapi. You can also choose the `Name` for your application, which is somewhat important, because it will be part of the address your users will use to access the web application. Under **Build** you could add environment variables for build and runtime. At the moment there is two important environment variables you need to set, `VITE_API_URL` and `API_BASE_URL` which should point to the URL of you api server. For example ``` VITE_API_URL = https://api-my-desdeo-app.2.rahtiapp.fi API_BASE_URL = https://api-my-desdeo-app.2.rahtiapp.fi ``` It is unlikely you will need to touch anything under **Deploy** or **Advanced Options**. Once you click `Create` the system should download your code, build it, and run it. Note You are highly likely to encounter error `exit status 137` when building your app. This is because the build node ran out of memory. Luckily, this is not difficult to fix. You will just need to open the **YAML** of your build config and change `spec.resources`. 4000 Mi should be enough. ``` resources: limits: memory: 4000Mi ``` ## PostgreSQL database DESDEO webapi uses a PostgreSQL to store information about users and problems. That is why you are also going to need PostgreSQL database. If you are working on Rahti you have at least two reasonably good options for getting one running. The first one is [Pukki DBaaS](https://pukki.dbaas.csc.fi/) provided by CSC and the second one is hosting one on Rahti by choosing a PostgreSQL image from the developer catalog. If you want to use Pukki, you first need to [add the Pukki service to your computing project](https://docs.csc.fi/accounts/how-to-add-service-access-for-project/). Then login to [Pukki](https://pukki.dbaas.csc.fi/) and add a database to your project by clicking the `Launch Instance` button. Give a name to the instance. You probably don't need to adjust Volume Size, Datastore, or Flavor settings. In **Database Access**, you need to input the web addresses the database will be accessed from. If you are hosting DESDEO on Rahti, the address should be `86.50.229.150/32`. In **Initialize Databases** you can setup an initial database and add an admin username and password. You should do that. You don't need to touch anything under **Advanced**. If you are hosting the database on Rahti, you just select the image and then input the initial settings similarly to what you would on Pukki. For your web application to work, webapi also needs to know how to access the database. Make sure to set up the environmental variables the way shown in [DESDEO webapi](#desdeo-webapi). You can store the address and login details as a secret in Rahti and then pass them on to builds and pods through the resource configuration. Once your webapi knows how to access the database, you will need to initialize the database to create user accounts and passwords (and possibly other things). The easiest way is to connect to the database from your own computer. To do this, you will first need to add your IP to the database access list. Then set up environmental variables associated with the database as you would for the [DESDEO webapi](#desdeo-webapi). You can modify the script `desdeo/api/db_init.py` to do something outside the debug mode or create a custom script for your project that will set up the database. ## Troubleshooting If you manage get webapi and webui running, but you are unable to get past the login page or do much else, your webui probably does not know where the webapi server is running. The address is supposed to be in the two environment variables. If you are encountering `Login attempt failed. Please check your username and password.` errors in the login screen, and you think you have the correct username and password, it is likely that webapi is not connecting to the [database](#postgresql-database) correctly or you have not initialized the database correctly. Check that you have set the environment variables for the api. # How to use the NAUTILUS Navigator method ## Introduction Information about the method. ## Setting up the problem While the implemented NAUTILUS Navigator method can be used for any kind of problem (analytical, data-based, etc.), it is recommended to be used with a data-based problem. More specifically, it is recommended to be used with a problem with a known approximation of the Pareto front. This is because the method conducts many optimization runs for each step. While optimization on an approximation of a Pareto front is quick and easy, optimization on simulation based problem or even just analytical problems can be very time consuming. You can use other methods in this framework to find an approximation of the Pareto front. To set up a problem, you can start with a problem object as described in ["How to define a problem"](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_define_a_problem/index.md). Then you can add the approximation of the Pareto front as follows: ``` from desdeo.problem.schema import DiscreteRepresentation dis_def = DiscreteRepresentation( variable_values={ "var_1_data": list_of_var_1_values, "var_2_data": list_of_var_2_values }, objective_values={ "obj_1_data": list_of_obj_1_values, "obj_2_data": list_of_obj_2_values }, ) ``` You are now ready to use the NAUTILUS Navigator method. ## Using the method ### Step 1: Import the relevant methods: - `navigator_init` to initialize the method. This method takes the problem object and creates the initial reachable ranges. - `navigator_all_steps` to run the method until the Pareto front is reached. This method takes the problem object, the return value of `navigator_init`, the number of steps to take, and a reference point. It returns information about all the steps taken as a list of `NAUTILUS_Response` objects. - `NAUTILUS_Response` is the object that contains information about the step taken. It is returned by `navigator_init` (single object) and `navigator_all_steps` (as a list). It contains the following fields: - `step`: The step number. - `distance_to_front`: The relative distance to the Pareto front at the end of the step. This is calculated as the ratio of the distance between the `navigation_point` and `reachable_solution` and the distance between the `navigation_point` and the `nadir point`. - `navigation_point`: The point from which the lower and upper reachable bounds are calculated for the current step. - `reachable_solution`: The reachable solution at the end of the current path. - `reachable_bounds`: The reachable ranges at the current step. - `reference_point`: The reference point used in the step. - `step_back_index` and `get_current_path` are explained later. ``` from desdeo.mcdm.nautilus_navigator import ( navigator_init, navigator_all_steps, NAUTILUS_Response, # You don't actually need to import this, but it is useful to know the structure of the return value of navigator_all_steps step_back_index, get_current_path ) ``` ### Step 2: Initialize the method: Initialize the method by calling `navigator_init` with the problem object. ``` initial_response = navigator_init(problem) ``` At this point, the analyst may use the `initial_response` to visualize the reachable ranges and the reachable solutions to the DM. Get the aspiration levels from the DM as a dictionary with the objective names as keys and the aspiration levels as values. ### Step 3: Run the method: Run the method by calling `navigator_all_steps` with the problem object, the return value of `navigator_init`, the number of steps to take, and the aspiration levels. ``` # Set preferences and parameters reference_point = { "SomeObj": 0.5, "SomeOtherObj": 200.5, "YetAnotherObj": -22, } total_steps = 100 # Run the method all_responses: list[NAUTILUS_Response] = navigator_all_steps( problem, total_steps, reference_point, [initial_response] # Note that this is a list of NAUTILUS_Response objects ) # Append the responses to the archive of responses all_responses = [initial_response, *all_responses] ``` At this point, the analyst may use the `all_responses` to visualize the reachable ranges and the reachable solutions of each step to the DM. Even though all steps have been evaluated at this point, the analyst (or the GUI) should only visualize this steps one at a time, at a certain rate (say, 1 step per second). This will allow the DM to think that they are navigating the solution space without it consuming too much time. One way to get the information to be visualized: ``` lower_bounds = pl.DataFrame( [response.reachable_bounds["lower_bounds"] for response in all_responses] ) upper_bounds = pl.DataFrame( [response.reachable_bounds["upper_bounds"] for response in all_responses] ) reference_point = pl.DataFrame( [response.reference_point for response in all_responses[1:]] ) ``` This will give you the lower and upper bounds of the reachable ranges and the reference points used in each step as a DataFrame. > Note > > Maximization is already handled in all of these steps. You should provide the real (meaningful) values of the objectives to the method. The method will handle the maximization internally. Similarly, the returned values are already the true objective values and can be visualized to the DM as directly. ### Step 4: Take a step back Let's say that the DM wants to take a step back to a previous step. It does not matter when they make this choice, the `all_responses` list already contains all possible steps. The analyst should copy the response from the step that the DM wants to go back to and append it to the `all_responses` list. Then, `navigator_all_steps` can be called with the new aspiration levels and the number of remaining steps. ``` go_back_to = 3 steps_remaining = total_steps - go_back_to reference_point = { "SomeObj": 4.5, "SomeOtherObj": 100.5, "YetAnotherObj": -2, } all_responses = [ *all_responses, all_responses[step_back_index(all_responses, go_back_to)], ] new_responses = navigator_all_steps( problem, steps_remaining, reference_point, all_responses, create_proximal_solver ) all_responses = [*all_responses, *new_responses] ``` Note, as all responses are appended to the same list, finding out the index of the step to go back to is not trivial. The `step_back_index` function can be used to find the index of the step to go back to. It finds all responses that have a `step_number` equal to the `go_back_to` and returns the index of the last such response. This is because the last such response is the one that was appended to the `all_responses` list most recently. Moreover, the `get_current_path` function can be used to get the current path of the method. This is useful for visualizing the current path to the DM. ``` current_path = get_current_path(all_responses) responses_to_visualize = [all_responses[i] for i in current_path] ``` # How to use the Pareto Navigator method ## Introduction This is a how-to guide to use the Pareto Navigator method. The method is implemented according to the description in [1]. ## Setting up the problem The implemented Pareto Navigator method is to be used used with a problem with a known approximation of the Pareto front. This is because the method assumes a set of Pareto optimal solutions to get started. To set up a problem, you can start with a problem object as described in ["How to define a problem"](https://desdeo.readthedocs.io/en/latest/howtoguides/how_to_define_a_problem/index.md). Then you can add the approximation of the Pareto front as follows: ``` from desdeo.problem.schema import DiscreteRepresentation dis_def = DiscreteRepresentation( variable_values={ "var_1_data": list_of_var_1_values, "var_2_data": list_of_var_2_values }, objective_values={ "obj_1_data": list_of_obj_1_values, "obj_2_data": list_of_obj_2_values }, ) ``` You are now ready to use the Pareto Navigator method. ## Using the method ### Step 1: Import the relevant methods: - `calculate_adjusted_speed` to determine the speed (step length) of the navigation. This method takes a list of allowed speeds, the desired speed and optionally a value to scale the speed. It returns an adjusted speed. - `calculate_all_solutions` to compute a set number of solutions in the current direction. Takes the problem object, the currently navigated solution, the current speed, the number of solutions to compute, and preference information as either a reference point or classification. ``` from desdeo.mcdm.pareto_navigator import ( calculate_adjusted_speed, calculate_all_solutions ) ``` ### Step 2: Initialization: First define a list of allowed speeds and the desired speed to calculate the adjusted speed by calling `calculate_adjusted_speed`, and set the starting point, provided by the DM. ``` allowed_speeds = [1, 2, 3, 4, 5] speed = 1 adjusted_speed = calculate_adjusted_speed(allowed_speeds, speed) # Set the starting point current_solution = { "SomeObj": 1.38, "SomeOtherObj": 0.62, "YetAnotherObj": -35.33 } ``` ### Step 3: Run the method: Get preference information from the DM as either a reference point or classification, where `<` means the objective function value should improve, `>` means the objective function value may worsen and `=` means the objective function value should remain the same. Run the method by calling `calculate_all_solutions` with the problem object, the currently navigated solution, the current speed, the number of solutions to compute, and the preference information. ``` # Set parameters and preferences as classification total_solutions = 200 preference_information = { "classification": { "SomeObj": "<", "SomeOtherObj": ">", "YetAnotherObj": "=" } } # Run the method solutions = calculate_all_solutions(problem, current_solution, adjusted_speed, num_solutions, preference_information) ``` ## References \[1\]: Eskelinen, P., Miettinen, K., Klamroth, K., & Hakanen, J. (2010). Pareto Navigator for Interactive Nonlinear Multiobjective Optimization. OR Spectrum, 32, 211-227. # How to add a solution description to a problem By default, the web-GUI shows a solution as a list of objective values. For many problems, those numbers alone do not tell a decision maker what the solution actually means. They may also want to know which investments it makes, what each part of the cost is, or how many hours of demand go unmet. A `SolutionDescriptionMetaData` attached to a problem tells the web-API how to turn any solution of that problem into a short, human-readable text. The web-GUI then shows that text in a "Solution Description" panel next to the selected solution. This guide explains how a description is defined, how to attach one to a problem, and what to watch out for. Where it is used The NIMBUS and CUMULUS views in the web-GUI show the description panel. It appears whenever the problem has solution description metadata, unless the problem also has forest (map) metadata, in which case the map is shown instead. ## The idea: a template made of parts A description is a list of [`DescriptionPart`](https://github.com/industrial-optimization-group/DESDEO/blob/master/desdeo/api/models/problem.py) objects. When a solution is described, each part is rendered to a string, and the strings are joined with `separator` (a newline by default): ``` from desdeo.api.models.problem import DescriptionPart parts = [ DescriptionPart(text="Investment decisions:"), DescriptionPart(label=" Battery capacity", symbol="E", format_spec=".1f", suffix=" kWh"), DescriptionPart(label=" Solar panels", symbol="n", format_spec=".0f"), DescriptionPart( label=" Solar panel cost", expression=["Multiply", 200, "n"], format_spec=".0f", suffix=" €", ), ] ``` For a solution with `E = 12.0` and `n = 8`, this renders as: ``` Investment decisions: Battery capacity: 12.0 kWh Solar panels: 8 Solar panel cost: 1600 € ``` The panel preserves whitespace, so leading spaces in a label indent that line. ### Fields of a part Each part should set exactly one of `text`, `symbol` or `expression`: | Field | Meaning | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | | `text` | Static text, included as is. `label`, `format_spec` and `suffix` are ignored. | | `symbol` | The symbol of a value in the solution (see [below](#which-values-are-available)). | | `expression` | A [MathJSON](https://desdeo.readthedocs.io/en/latest/explanation/problem_format/index.md) expression, evaluated with the solution's values. | The remaining fields only apply to `symbol` and `expression` parts: | Field | Meaning | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `format_spec` | A Python [format spec](https://docs.python.org/3/library/string.html#formatspec) applied to the value, e.g. `".0f"`, `".2f"`, `",.0f"`, `".1%"`. Without it, the value is shown with `str()`. | | `label` | Placed before the value, followed by `": "`. | | `suffix` | Appended right after the value, e.g. a unit such as `" kWh"`. Include the leading space yourself. | A rendered part therefore looks like `