├── pyproject.toml ├── .gitignore ├── pyMMAopt ├── __init__.py ├── __about__.py ├── constraints.py ├── mma_solver.py └── mma.py ├── examples ├── corner_mesh.geo ├── beam_uniform.geo ├── quadratic_pde.py └── compliance.py ├── README.md ├── CONTRIBUTING.md ├── setup.py ├── setup.cfg ├── NOTICE ├── .github └── workflows │ └── publish-to-test-pypi.yml ├── tests ├── test_analytical.py ├── test_restart.py └── test_compliance.py ├── CODE_OF_CONDUCT.md └── LICENSE /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=42", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | *.prof 4 | MANIFEST 5 | dist/ 6 | build/ 7 | .coverage 8 | .cache/ 9 | *.egg-info/ 10 | *.eggs/ 11 | .pytest_cache/ 12 | *.pvd 13 | *.vtu 14 | *.h5 15 | -------------------------------------------------------------------------------- /pyMMAopt/__init__.py: -------------------------------------------------------------------------------- 1 | from .__about__ import __version__ 2 | from .mma import MMAClient 3 | from .mma_solver import MMASolver 4 | from .constraints import ReducedInequality 5 | 6 | __all__ = [ 7 | "__version__", 8 | "MMAClient", 9 | ] 10 | -------------------------------------------------------------------------------- /pyMMAopt/__about__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | 4 | __author__ = "Miguel Salazar de Troya" 5 | __email__ = "salazardetro1@llnl.gov" 6 | __copyright__ = "Copyright (c) 2019 {} <{}>".format(__author__, __email__) 7 | __license__ = "License :: OSI Approved :: MIT License" 8 | __version__ = "0.0.8" 9 | __status__ = "Development Status :: 4 - Beta" 10 | -------------------------------------------------------------------------------- /examples/corner_mesh.geo: -------------------------------------------------------------------------------- 1 | Point(1) = {0., 0., 0., 0.01}; 2 | Point(2) = {10., 0., 0., 0.5}; 3 | Point(3) = {10., 10., 0., 0.5}; 4 | Point(4) = {0., 10., 0., 0.5}; 5 | //+ 6 | Line(1) = {1, 2}; 7 | //+ 8 | Line(2) = {2, 3}; 9 | //+ 10 | Line(3) = {3, 4}; 11 | //+ 12 | Line(4) = {4, 1}; 13 | //+ 14 | Curve Loop(1) = {3, 4, 1, 2}; 15 | //+ 16 | Plane Surface(1) = {1}; 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pyMMAopt 2 | [![DOI](https://zenodo.org/badge/317367772.svg)](https://zenodo.org/badge/latestdoi/317367772) 3 | 4 | Python implementation of the Method of Moving Asymptotes optimization algorithm 5 | described in 6 | [Svanberg, K., The method of moving asymptotes- a new method for structural optimization. International journal for numerical methods in engineering, 1987. 24(2): p. 359](https://onlinelibrary.wiley.com/doi/abs/10.1002/nme.1620240207). Originally implemented in [GetDP](https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=717799) [project](https://gitlab.onelab.info/getdp/getdp). 7 | 8 | LLNL Release Number: LLNL-CODE-817087 9 | 10 | # Install 11 | ``` 12 | pip3 install . 13 | ``` 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to pyMMAopt 2 | 3 | We welcome contributions to pyMMAopt. To do so please submit a pull request through our 4 | pyMMAopt github page at https://github.com/LLNL/pyMMAopt. 5 | 6 | All contributions to pyMMAopt must be made under the MIT License. 7 | 8 | Any questions can be sent to salazardetro1@llnl.gov. 9 | 10 | # Attribution 11 | 12 | The pyMMAopt project uses git's commit history to track contributions from individual developers. 13 | 14 | Since we want everyone to feel they are getting the proper attribution for their contributions, please add your name to 15 | the list below as part of your commit. 16 | 17 | # Contributors (In Alphabetical Order) 18 | 19 | * Miguel Salazar, LLNL 20 | -------------------------------------------------------------------------------- /examples/beam_uniform.geo: -------------------------------------------------------------------------------- 1 | // This code was created by pygmsh vunknown. 2 | p0 = newp; 3 | Point(p0) = {0.0, 0.0, 0.0, 1.0}; 4 | p3 = newp; 5 | Point(p3) = {100.0, 0.0, 0.0, 1.0}; 6 | p4 = newp; 7 | Point(p4) = {100.0, 16.0, 0.0, 0.08}; 8 | p5 = newp; 9 | Point(p5) = {100.0, 24.0, 0.0, 0.08}; 10 | p6 = newp; 11 | Point(p6) = {100.0, 40.0, 0.0, 1.0}; 12 | p9 = newp; 13 | Point(p9) = {0.0, 40.0, 0.0, 1.0};//+ 14 | //+ 15 | Line(1) = {6, 1}; 16 | //+ 17 | Line(2) = {1, 2}; 18 | //+ 19 | Line(3) = {2, 3}; 20 | //+ 21 | Line(4) = {3, 4}; 22 | //+ 23 | Line(5) = {4, 5}; 24 | //+ 25 | Line(6) = {5, 6}; 26 | //+ 27 | Curve Loop(1) = {6, 1, 2, 3, 4, 5}; 28 | //+ 29 | Plane Surface(1) = {1}; 30 | //+ 31 | Transfinite Surface {1} = {6, 5, 2, 1}; 32 | //+ 33 | Transfinite Curve {6, 2} = 26 Using Progression 1; 34 | //+ 35 | Transfinite Curve {1} = 11 Using Progression 1; 36 | //+ 37 | Transfinite Curve {5, 3} = 5 Using Progression 1; 38 | //+ 39 | Transfinite Curve {4} = 3 Using Progression 1; 40 | //+ 41 | Physical Curve(3) = {1}; 42 | //+ 43 | Physical Curve(4) = {4}; 44 | Physical Surface(1) = {1}; 45 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | from setuptools import setup, find_packages 5 | 6 | base_dir = os.path.abspath(os.path.dirname(__file__)) 7 | about = {} 8 | with open(os.path.join(base_dir, "pyMMAopt", "__about__.py"), "rb") as f: 9 | exec(f.read(), about) 10 | 11 | if __name__ == "__main__": 12 | setup( 13 | name="pyMMAopt", 14 | version=about["__version__"], 15 | packages=find_packages(), 16 | author=about["__author__"], 17 | author_email=about["__email__"], 18 | install_requires=["numpy", "numexpr"], 19 | description="MMA optimization algorithm in python", 20 | license=about["__license__"], 21 | classifiers=[ 22 | about["__license__"], 23 | about["__status__"], 24 | # See for all classifiers. 25 | "Operating System :: OS Independent", 26 | "Programming Language :: Python", 27 | "Programming Language :: Python :: 3", 28 | "Topic :: Scientific/Engineering", 29 | "Topic :: Scientific/Engineering :: Mathematics", 30 | ], 31 | python_requires=">=3") 32 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = pyMMAopt 3 | version = 0.0.8 4 | author = GetDP Project 5 | author_email = salazardetro1@llnl.gov 6 | description = MMA algorithm in python 7 | url = https://github.com/LLNL/pyMMAopt 8 | long_description = file: README.md 9 | long_description_content_type = text/markdown 10 | license = GPL 11 | license_files = LICENSE 12 | platforms = any 13 | # See for all classifiers. 14 | classifiers = 15 | Development Status :: 4 - Beta 16 | Intended Audience :: Science/Research 17 | License :: OSI Approved :: GNU General Public License version 2.0 18 | Operating System :: OS Independent 19 | Programming Language :: Python 20 | Programming Language :: Python :: 3 21 | Programming Language :: Python :: 3.5 22 | Programming Language :: Python :: 3.6 23 | Programming Language :: Python :: 3.7 24 | Programming Language :: Python :: 3.8 25 | Topic :: Utilities 26 | 27 | [options] 28 | packages = find: 29 | install_requires = 30 | importlib_metadata 31 | python_requires = >=3.5 32 | setup_requires = 33 | numpy 34 | numexpr 35 | setuptools>=42 36 | wheel 37 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | This work was produced under the auspices of the U.S. Department of Energy by 2 | Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. 3 | 4 | This work was prepared as an account of work sponsored by an agency of the 5 | United States Government. Neither the United States Government nor Lawrence 6 | Livermore National Security, LLC, nor any of their employees makes any warranty, 7 | expressed or implied, or assumes any legal liability or responsibility for the 8 | accuracy, completeness, or usefulness of any information, apparatus, product, or 9 | process disclosed, or represents that its use would not infringe privately owned 10 | rights. Reference herein to any specific commercial product, process, or service 11 | by trade name, trademark, manufacturer, or otherwise does not necessarily 12 | constitute or imply its endorsement, recommendation, or favoring by the United 13 | States Government or Lawrence Livermore National Security, LLC. The views and 14 | opinions of authors expressed herein do not necessarily state or reflect those 15 | of the United States Government or Lawrence Livermore National Security, LLC, 16 | and shall not be used for advertising or product endorsement purposes. 17 | -------------------------------------------------------------------------------- /.github/workflows/publish-to-test-pypi.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python 🐍 distributions 📦 to PyPI and TestPyPI 2 | on: push 3 | 4 | jobs: 5 | build-n-publish: 6 | name: Build and publish Python 🐍 distributions 📦 to PyPI and TestPyPI 7 | runs-on: ubuntu-18.04 8 | steps: 9 | - uses: actions/checkout@main 10 | - name: Set up Python 3.9 11 | uses: actions/setup-python@v1 12 | with: 13 | python-version: 3.9 14 | - name: Install pypa/build 15 | run: >- 16 | python -m 17 | pip install 18 | build 19 | --user 20 | - name: Build a binary wheel and a source tarball 21 | run: >- 22 | python -m 23 | build 24 | --sdist 25 | --wheel 26 | --outdir dist/ 27 | . 28 | - name: Publish distribution 📦 to Test PyPI 29 | uses: pypa/gh-action-pypi-publish@master 30 | with: 31 | skip_existing: True 32 | password: ${{ secrets.TEST_PYPI_API_TOKEN }} 33 | repository_url: https://test.pypi.org/legacy/ 34 | - name: Publish distribution 📦 to PyPI 35 | if: startsWith(github.ref, 'refs/tags') 36 | uses: pypa/gh-action-pypi-publish@master 37 | with: 38 | password: ${{ secrets.PYPI_API_TOKEN }} -------------------------------------------------------------------------------- /tests/test_analytical.py: -------------------------------------------------------------------------------- 1 | from firedrake import * 2 | from firedrake_adjoint import * 3 | from pyMMAopt import MMASolver, ReducedInequality 4 | 5 | def test_analytical(): 6 | mesh = UnitSquareMesh(1, 1, quadrilateral=True) 7 | DG = VectorFunctionSpace(mesh, "DG", 0) 8 | X = Function(DG) 9 | with stop_annotating(): 10 | X.interpolate(Constant((1.234, 2.345))) 11 | x, y = split(X) 12 | J = assemble(sqrt(y) * dx) 13 | G1 = assemble(((2.0 * x) ** 3 - y) * dx) 14 | G2 = assemble(((-1.0 * x + 1.0) ** 3 - y) * dx) 15 | 16 | m = Control(X) 17 | 18 | Jhat = ReducedFunctional(J, m) 19 | G1hat = ReducedFunctional(G1, m) 20 | G2hat = ReducedFunctional(G2, m) 21 | print(f"{G1hat.derivative().dat.data_ro}") 22 | print(f"{G2hat.derivative().dat.data_ro}") 23 | 24 | problem = MinimizationProblem( 25 | Jhat, 26 | bounds=(0.0, 100.0), 27 | constraints=[ 28 | ReducedInequality(G1hat, 1e-5, Control(G1), normalized=False), 29 | ReducedInequality(G2hat, 1e-5, Control(G2), normalized=False), 30 | ], 31 | ) 32 | 33 | parameters_mma = { 34 | "move": 0.1, 35 | "maximum_iterations": 10, 36 | "m": 2, 37 | "IP": 0, 38 | "tol": 1e-9, 39 | "accepted_tol": 1e-8, 40 | "gcmma": True, 41 | } 42 | solver = MMASolver(problem, parameters=parameters_mma) 43 | results = solver.solve() 44 | rho_opt = results["control"] 45 | assert abs(Jhat(rho_opt) - 0.5443418101973394) < 1e-7 46 | solution = Function(DG).interpolate(Constant((0.33332924, 0.29630801))) 47 | assert errornorm(rho_opt, solution) < 1e-7 48 | -------------------------------------------------------------------------------- /tests/test_restart.py: -------------------------------------------------------------------------------- 1 | from firedrake import * 2 | from firedrake_adjoint import * 3 | from pyMMAopt import MMASolver, ReducedInequality 4 | 5 | import os, signal, itertools 6 | 7 | 8 | def test_save_with_signal(): 9 | mesh = UnitSquareMesh(10, 10) 10 | DG = FunctionSpace(mesh, "DG", 0) 11 | print(f"DOFS: {DG.dim()}") 12 | rho = interpolate(Constant(1.0), DG) 13 | J = assemble(rho * rho * rho * dx) 14 | G = assemble(rho * dx) 15 | m = Control(rho) 16 | 17 | g_counter = itertools.count() 18 | 19 | def deriv_cb(j, dj, rho): 20 | iter = next(g_counter) 21 | print(iter) 22 | if iter % 10 == 0 and iter > 0: 23 | os.kill(os.getpid(), signal.SIGUSR1) 24 | 25 | Jhat = ReducedFunctional(J, m, derivative_cb_post=deriv_cb) 26 | Ghat = ReducedFunctional(G, m) 27 | total_area = assemble(Constant(1.0) * dx(domain=mesh), annotate=False) 28 | Glimit = total_area * 50 29 | Gcontrol = Control(G) 30 | 31 | problem = MinimizationProblem( 32 | Jhat, 33 | bounds=(1e-5, 100.0), 34 | constraints=[ 35 | ReducedInequality(Ghat, Glimit, Gcontrol), 36 | ], 37 | ) 38 | 39 | parameters_mma = { 40 | "move": 0.1, 41 | "maximum_iterations": 10, 42 | "m": 1, 43 | "IP": 0, 44 | "tol": 1e-9, 45 | "accepted_tol": 1e-8, 46 | "norm": "L2", 47 | } 48 | solver = MMASolver(problem, parameters=parameters_mma) 49 | results = solver.solve() 50 | rho_sol = results["control"] 51 | 52 | assert os.path.isfile("checkpoint_iter_10.h5") 53 | 54 | parameters_mma["restart_file"] = "./checkpoint_iter_10.h5" 55 | parameters_mma["maximum_iterations"] = 0 56 | solver = MMASolver(problem, parameters=parameters_mma) 57 | results = solver.solve() 58 | rho_restart = results["control"] 59 | assert errornorm(rho_sol, rho_restart) < 1e-2 60 | 61 | -------------------------------------------------------------------------------- /pyMMAopt/constraints.py: -------------------------------------------------------------------------------- 1 | from pyadjoint.optimization.constraints import InequalityConstraint 2 | from firedrake import warning 3 | from pyadjoint import stop_annotating 4 | 5 | from firedrake.petsc import PETSc 6 | from firedrake import COMM_WORLD 7 | print = lambda x: PETSc.Sys.Print(x, comm=COMM_WORLD) 8 | 9 | class ReducedInequality(InequalityConstraint): 10 | """This class represents constraints of the form 11 | Ghat(m) - Glimit >= 0 12 | where m is the parameter. 13 | For Ghat(m) - Glimit <= 0, pass lower=True 14 | """ 15 | 16 | def __init__(self, Ghat, Glimit, Gcontrol, lower=True, normalized=True): 17 | self.Ghat = Ghat 18 | self.Glimit = float(Glimit) 19 | self.Gcontrol = Gcontrol 20 | self.lower = lower 21 | self.normalized = normalized 22 | if abs(Glimit) < 1e-4 and normalized: 23 | warning(f"Normalized is on with a very small bound {Glimit}") 24 | 25 | def function(self, m): 26 | 27 | # Compute the integral of the control over the domain 28 | integral = self.Gcontrol.tape_value() 29 | print(f"Value: {integral}, Constraint {self.Glimit}") 30 | with stop_annotating(): 31 | if self.lower: 32 | if self.normalized: 33 | value = -integral / self.Glimit + 1.0 34 | else: 35 | value = -integral + self.Glimit 36 | else: 37 | if self.normalized: 38 | value = integral / self.Glimit - 1.0 39 | else: 40 | value = integral - self.Glimit 41 | return [value] 42 | 43 | def jacobian(self, m): 44 | 45 | with stop_annotating(): 46 | gradients = self.Ghat.derivative() 47 | with gradients.dat.vec as v: 48 | if self.lower: 49 | if self.normalized: 50 | v.scale(-1.0 / self.Glimit) 51 | else: 52 | v.scale(-1.0) 53 | else: 54 | if self.normalized: 55 | v.scale(1.0 / self.Glimit) 56 | else: 57 | v.scale(1.0) 58 | return [gradients] 59 | 60 | def output_workspace(self): 61 | return [0.0] 62 | 63 | def length(self): 64 | """Return the number of components in the constraint vector (here, one).""" 65 | return 1 66 | -------------------------------------------------------------------------------- /examples/quadratic_pde.py: -------------------------------------------------------------------------------- 1 | from firedrake import * 2 | from firedrake.petsc import PETSc 3 | from firedrake_adjoint import * 4 | from pyMMAopt import MMASolver 5 | import os 6 | 7 | print = lambda x: PETSc.Sys.Print(x, comm=COMM_SELF) 8 | 9 | import numpy as np 10 | import argparse 11 | 12 | 13 | parser = argparse.ArgumentParser(description="Simple optimization problem") 14 | parser.add_argument( 15 | "--n_vars", 16 | action="store", 17 | dest="n_vars", 18 | type=int, 19 | help="Number of design variables", 20 | default=200, 21 | ) 22 | args = parser.parse_args() 23 | n_vars = args.n_vars 24 | grid_resol = int(np.sqrt(n_vars)) 25 | 26 | 27 | mesh = Mesh("./corner_mesh.msh") 28 | DG = FunctionSpace(mesh, "DG", 0) 29 | x, y = SpatialCoordinate(mesh) 30 | rho = interpolate(Constant(1.0), DG) 31 | 32 | solution_pvd = File("quadratic_sol.pvd") 33 | derivative_pvd = File("derivative.pvd") 34 | rho_viz = Function(DG) 35 | der_viz = Function(DG) 36 | 37 | 38 | def deriv_cb(j, dj, rho): 39 | with stop_annotating(): 40 | rho_viz.assign(rho) 41 | solution_pvd.write(rho_viz) 42 | 43 | der_viz.assign(dj) 44 | derivative_pvd.write(der_viz) 45 | 46 | 47 | J = assemble(Constant(1e4) * rho * rho * dx) 48 | G = assemble(rho * dx) 49 | m = Control(rho) 50 | Jhat = ReducedFunctional(J, m, derivative_cb_post=deriv_cb) 51 | Ghat = ReducedFunctional(G, m) 52 | total_area = assemble(Constant(1.0) * dx(domain=mesh), annotate=False) 53 | Glimit = total_area * 20.0 54 | Gcontrol = Control(G) 55 | 56 | 57 | class ReducedInequality(InequalityConstraint): 58 | def __init__(self, Ghat, Glimit, Gcontrol): 59 | self.Ghat = Ghat 60 | self.Glimit = float(Glimit) 61 | self.Gcontrol = Gcontrol 62 | 63 | def function(self, m): 64 | # Compute the integral of the control over the domain 65 | integral = self.Gcontrol.tape_value() 66 | print(f"Constraint function: {integral}, Constraint upper bound {self.Glimit}") 67 | with stop_annotating(): 68 | value = -integral / self.Glimit + 1.0 69 | return [value] 70 | 71 | def jacobian(self, m): 72 | with stop_annotating(): 73 | gradients = self.Ghat.derivative() 74 | with gradients.dat.vec as v: 75 | v.scale(-1.0 / self.Glimit) 76 | return [gradients] 77 | 78 | def output_workspace(self): 79 | return [0.0] 80 | 81 | def length(self): 82 | """Return the number of components in the constraint vector (here, one).""" 83 | return 1 84 | 85 | 86 | problem = MinimizationProblem( 87 | Jhat, 88 | bounds=(1e-5, 100.0), 89 | constraints=[ 90 | ReducedInequality(Ghat, Glimit, Gcontrol), 91 | ], 92 | ) 93 | 94 | 95 | parameters_mma = { 96 | "move": 0.1, 97 | "maximum_iterations": 5, 98 | "m": 1, 99 | "IP": 0, 100 | "tol": 1e-9, 101 | "accepted_tol": 1e-8, 102 | "norm": "L2", 103 | } 104 | solver = MMASolver(problem, parameters=parameters_mma) 105 | rho_sol = solver.solve() 106 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Code of Conduct" 3 | --- 4 | 5 | ## Community Code of Conduct 6 | 7 | ### Our Pledge 8 | 9 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 10 | 11 | ### Our Standards 12 | 13 | Examples of behavior that contributes to creating a positive environment include: 14 | 15 | * Using welcoming and inclusive language 16 | * Being respectful of differing viewpoints and experiences 17 | * Gracefully accepting constructive criticism 18 | * Focusing on what is best for the community 19 | * Showing empathy towards other community members 20 | 21 | Examples of unacceptable behavior by participants include: 22 | 23 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 24 | * Trolling, insulting/derogatory comments, and personal or political attacks 25 | * Public or private harassment 26 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 27 | * Other conduct which could reasonably be considered inappropriate in a professional setting 28 | 29 | ### Our Responsibilities 30 | 31 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 32 | 33 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 34 | 35 | ### Scope 36 | 37 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the lestofire project or its community. Examples of representing the project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of the project may be further defined and clarified by lestofire maintainers. 38 | 39 | ### Enforcement 40 | 41 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at lestofire or the LLNL GitHub Admins at [github-admin@llnl.gov](mailto:github-admin@llnl.gov) . The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 42 | 43 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project or organization's leadership. 44 | 45 | ### Attribution 46 | 47 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/) ([version 1.4](http://contributor-covenant.org/version/1/4)). 48 | -------------------------------------------------------------------------------- /tests/test_compliance.py: -------------------------------------------------------------------------------- 1 | from firedrake import * 2 | from firedrake_adjoint import * 3 | import pytest 4 | import numpy as np 5 | 6 | from pyMMAopt import MMASolver, ReducedInequality 7 | 8 | 9 | @pytest.mark.parametrize( 10 | "norm,result", 11 | [["l2", 7.454771069410802], ["L2", 7.420380654729631]], 12 | ) 13 | def test_compliance(norm, result): 14 | mesh = RectangleMesh(100, 30, 10, 3) 15 | 16 | V = VectorFunctionSpace(mesh, "CG", 1) 17 | u, v = TrialFunction(V), TestFunction(V) 18 | print(f"# DOFS: {V.dim()}") 19 | 20 | # Elasticity parameters 21 | E, nu = 1e0, 0.3 22 | mu, lmbda = Constant(E / (2 * (1 + nu))), Constant( 23 | E * nu / ((1 + nu) * (1 - 2 * nu)) 24 | ) 25 | 26 | # Helmholtz solver 27 | RHO = FunctionSpace(mesh, "DG", 0) 28 | rho = interpolate(Constant(0.1), RHO) 29 | af, b = TrialFunction(RHO), TestFunction(RHO) 30 | 31 | filter_radius = Constant(0.02) 32 | x, y = SpatialCoordinate(mesh) 33 | x_ = interpolate(x, RHO) 34 | y_ = interpolate(y, RHO) 35 | Delta_h = sqrt(jump(x_) ** 2 + jump(y_) ** 2) 36 | 37 | rhof = Function(RHO) 38 | solver_params = { 39 | "ksp_type": "preonly", 40 | "pc_type": "lu", 41 | "pc_factor_mat_solver_type": "mumps", 42 | "mat_mumps_icntl_14": 200, 43 | "mat_mumps_icntl_24": 1, 44 | } 45 | 46 | eps = Constant(1e-5) 47 | p = Constant(3.0) 48 | 49 | def simp(rho): 50 | return eps + (Constant(1.0) - eps) * rho ** p 51 | 52 | def epsilon(v): 53 | return sym(nabla_grad(v)) 54 | 55 | def sigma(v): 56 | return 2.0 * mu * epsilon(v) + lmbda * tr(epsilon(v)) * Identity(2) 57 | 58 | DIRICHLET = 1 59 | NEUMANN = 2 60 | load = Constant((0.0, -5.0)) 61 | 62 | c = Control(rho) 63 | 64 | def forward(rho): 65 | 66 | aH = filter_radius * jump(af) / Delta_h * jump(b) * dS + af * b * dx 67 | LH = rho * b * dx 68 | 69 | solve(aH == LH, rhof, solver_parameters=solver_params) 70 | rhofControl = Control(rhof) 71 | 72 | a = inner(simp(rhof) * sigma(u), epsilon(v)) * dx 73 | L = inner(load, v) * ds(NEUMANN) 74 | 75 | u_sol = Function(V) 76 | 77 | bcs = DirichletBC(V, Constant((0.0, 0.0)), DIRICHLET) 78 | 79 | solve(a == L, u_sol, bcs=bcs, solver_parameters=solver_params) 80 | 81 | return rhof, u_sol 82 | 83 | rhof, u_sol = forward(rho) 84 | solution_pvd = File("compliance_design.pvd") 85 | rho_viz = Function(RHO) 86 | 87 | def deriv_cb(j, dj, rho): 88 | with stop_annotating(): 89 | rho_viz.assign(rho) 90 | solution_pvd.write(rho_viz) 91 | 92 | J = assemble(Constant(1e-4) * inner(u_sol, load) * ds(NEUMANN)) 93 | Vol = assemble(rhof * dx) 94 | VolControl = Control(Vol) 95 | 96 | with stop_annotating(): 97 | Vlimit = assemble(Constant(1.0) * dx(domain=mesh)) * 0.5 98 | 99 | Jhat = ReducedFunctional(J, c, derivative_cb_post=deriv_cb) 100 | Volhat = ReducedFunctional(Vol, c) 101 | 102 | lb = 0.0 103 | ub = 1.0 104 | problem = MinimizationProblem( 105 | Jhat, 106 | bounds=(lb, ub), 107 | constraints=[ReducedInequality(Volhat, Vlimit, VolControl)], 108 | ) 109 | 110 | parameters_mma = { 111 | "move": 0.2, 112 | "maximum_iterations": 20, 113 | "m": 1, 114 | "IP": 0, 115 | "tol": 1e-6, 116 | "accepted_tol": 1e-4, 117 | "gcmma": True, 118 | "norm": norm, 119 | } 120 | solver = MMASolver(problem, parameters=parameters_mma) 121 | 122 | results = solver.solve() 123 | rho_opt = results["control"] 124 | 125 | final_cost_func = Jhat(rho_opt) 126 | 127 | assert np.allclose(final_cost_func, result, rtol=1e-5) 128 | 129 | 130 | if __name__ == "__main__": 131 | test_compliance("L2", 7.420380654729631) 132 | -------------------------------------------------------------------------------- /examples/compliance.py: -------------------------------------------------------------------------------- 1 | import firedrake as fd 2 | from firedrake import sqrt, jump, dx, ds, dS, inner, sym, nabla_grad, tr, Identity, grad 3 | import firedrake_adjoint as fda 4 | 5 | from pyMMAopt import MMASolver 6 | import argparse 7 | 8 | 9 | def compliance(): 10 | parser = argparse.ArgumentParser(description="Compliance problem with MMA") 11 | parser.add_argument( 12 | "--nref", 13 | action="store", 14 | dest="nref", 15 | type=int, 16 | help="Number of mesh refinements", 17 | default=2, 18 | ) 19 | parser.add_argument( 20 | "--uniform", 21 | action="store", 22 | dest="uniform", 23 | type=int, 24 | help="Use uniform mesh", 25 | default=0, 26 | ) 27 | parser.add_argument( 28 | "--inner_product", 29 | action="store", 30 | dest="inner_product", 31 | type=str, 32 | help="Inner product, euclidean or L2", 33 | default="L2", 34 | ) 35 | parser.add_argument( 36 | "--output_dir", 37 | action="store", 38 | dest="output_dir", 39 | type=str, 40 | help="Directory for all the output", 41 | default="./", 42 | ) 43 | args = parser.parse_args() 44 | nref = args.nref 45 | inner_product = args.inner_product 46 | output_dir = args.output_dir 47 | 48 | assert inner_product == "L2" or inner_product == "euclidean" 49 | 50 | mesh = fd.Mesh("./beam_uniform.msh") 51 | #mh = fd.MeshHierarchy(mesh, 2) 52 | #mesh = mh[-1] 53 | 54 | if nref > 0: 55 | mh = fd.MeshHierarchy(mesh, nref) 56 | mesh = mh[-1] 57 | elif nref < 0: 58 | raise RuntimeError("Non valid mesh argument") 59 | 60 | V = fd.VectorFunctionSpace(mesh, "CG", 1) 61 | u, v = fd.TrialFunction(V), fd.TestFunction(V) 62 | 63 | # Elasticity parameters 64 | E, nu = 1e0, 0.3 65 | mu, lmbda = fd.Constant(E / (2 * (1 + nu))), fd.Constant( 66 | E * nu / ((1 + nu) * (1 - 2 * nu)) 67 | ) 68 | 69 | # Helmholtz solver 70 | RHO = fd.FunctionSpace(mesh, "CG", 1) 71 | rho = fd.interpolate(fd.Constant(0.1), RHO) 72 | af, b = fd.TrialFunction(RHO), fd.TestFunction(RHO) 73 | 74 | #filter_radius = fd.Constant(0.2) 75 | #x, y = fd.SpatialCoordinate(mesh) 76 | #x_ = fd.interpolate(x, RHO) 77 | #y_ = fd.interpolate(y, RHO) 78 | #aH = filter_radius * inner(grad(af), grad(b)) * dx + af * b * dx 79 | #LH = rho * b * dx 80 | 81 | rhof = fd.Function(RHO) 82 | solver_params = { 83 | "ksp_type": "preonly", 84 | "pc_type": "lu", 85 | "pc_factor_mat_solver_type": "mumps", 86 | "mat_mumps_icntl_14": 200, 87 | "mat_mumps_icntl_24": 1, 88 | } 89 | #fd.solve(aH == LH, rhof, solver_parameters=solver_params) 90 | rhof.assign(rho) 91 | rhofControl = fda.Control(rhof) 92 | 93 | eps = fd.Constant(1e-5) 94 | p = fd.Constant(3.0) 95 | 96 | def simp(rho): 97 | return eps + (fd.Constant(1.0) - eps) * rho ** p 98 | 99 | def epsilon(v): 100 | return sym(nabla_grad(v)) 101 | 102 | def sigma(v): 103 | return 2.0 * mu * epsilon(v) + lmbda * tr(epsilon(v)) * Identity(2) 104 | 105 | DIRICHLET = 3 106 | NEUMANN = 4 107 | 108 | a = inner(simp(rhof) * sigma(u), epsilon(v)) * dx 109 | load = fd.Constant((0.0, -1.0)) 110 | L = inner(load, v) * ds(NEUMANN) 111 | 112 | u_sol = fd.Function(V) 113 | 114 | bcs = fd.DirichletBC(V, fd.Constant((0.0, 0.0)), DIRICHLET) 115 | 116 | fd.solve(a == L, u_sol, bcs=bcs, solver_parameters=solver_params) 117 | c = fda.Control(rho) 118 | J = fd.assemble(fd.Constant(1e-4) * inner(u_sol, load) * ds(NEUMANN)) 119 | Vol = fd.assemble(rhof * dx) 120 | VolControl = fda.Control(Vol) 121 | 122 | with fda.stop_annotating(): 123 | Vlimit = fd.assemble(fd.Constant(1.0) * dx(domain=mesh)) * 0.5 124 | 125 | rho_viz_f = fd.Function(RHO, name="rho") 126 | plot_file = f"{output_dir}/design_{inner_product}.pvd" 127 | controls_f = fd.File(plot_file) 128 | 129 | def deriv_cb(j, dj, rho): 130 | with fda.stop_annotating(): 131 | rho_viz_f.assign(rhofControl.tape_value()) 132 | controls_f.write(rho_viz_f) 133 | 134 | Jhat = fda.ReducedFunctional(J, c, derivative_cb_post=deriv_cb) 135 | Volhat = fda.ReducedFunctional(Vol, c) 136 | 137 | class VolumeConstraint(fda.InequalityConstraint): 138 | def __init__(self, Vhat, Vlimit, VolControl): 139 | self.Vhat = Vhat 140 | self.Vlimit = float(Vlimit) 141 | self.VolControl = VolControl 142 | 143 | def function(self, m): 144 | # Compute the integral of the control over the domain 145 | integral = self.VolControl.tape_value() 146 | with fda.stop_annotating(): 147 | value = -integral / self.Vlimit + 1.0 148 | return [value] 149 | 150 | def jacobian(self, m): 151 | with fda.stop_annotating(): 152 | gradients = self.Vhat.derivative() 153 | with gradients.dat.vec as v: 154 | v.scale(-1.0 / self.Vlimit) 155 | return [gradients] 156 | 157 | def output_workspace(self): 158 | return [0.0] 159 | 160 | def length(self): 161 | """Return the number of components in the constraint vector (here, one).""" 162 | return 1 163 | 164 | lb = 1e-5 165 | ub = 1.0 166 | problem = fda.MinimizationProblem( 167 | Jhat, 168 | bounds=(lb, ub), 169 | constraints=[VolumeConstraint(Volhat, Vlimit, VolControl)], 170 | ) 171 | 172 | parameters_mma = { 173 | "move": 0.2, 174 | "maximum_iterations": 200, 175 | "m": 1, 176 | "IP": 0, 177 | "tol": 1e-6, 178 | "accepted_tol": 1e-4, 179 | "norm": inner_product, 180 | #"norm": "euclidean", 181 | "gcmma": False, 182 | } 183 | solver = MMASolver(problem, parameters=parameters_mma) 184 | 185 | rho_opt = solver.solve() 186 | 187 | with open(f"{output_dir}/finished_{inner_product}.txt", "w") as f: 188 | f.write("Done") 189 | 190 | 191 | if __name__ == "__main__": 192 | compliance() 193 | -------------------------------------------------------------------------------- /pyMMAopt/mma_solver.py: -------------------------------------------------------------------------------- 1 | from pyadjoint.adjfloat import AdjFloat 2 | from pyadjoint.optimization.optimization_solver import OptimizationSolver 3 | from firedrake.petsc import PETSc 4 | import firedrake as fd 5 | from pyadjoint import stop_annotating 6 | from firedrake import COMM_WORLD, HDF5File 7 | from firedrake.tsfc_interface import TSFCKernel 8 | from pyop2.global_kernel import GlobalKernel 9 | import gc 10 | import petsc4py 11 | from mpi4py import MPI 12 | import time 13 | import signal 14 | 15 | try: 16 | from .mma import MMAClient 17 | except ImportError: 18 | print("You need to install MMA") 19 | raise 20 | import numpy 21 | 22 | 23 | def print(x): 24 | return PETSc.Sys.Print(x, comm=COMM_WORLD) 25 | 26 | 27 | def copy_vec_into_funct(func, vec): 28 | with func.dat.vec as a_vec: 29 | a_vec.array_w = vec 30 | 31 | 32 | def func_to_vec(func): 33 | with func.dat.vec_ro as func_vec: 34 | vec = func_vec.array 35 | return vec 36 | 37 | 38 | class MMASolver(OptimizationSolver): 39 | def __init__(self, problem, parameters=None): 40 | OptimizationSolver.__init__(self, problem, parameters) 41 | 42 | self.rf = self.problem.reduced_functional 43 | if len(self.rf.controls) > 1: 44 | raise RuntimeError("Only one control is possible for MMA") 45 | 46 | if isinstance(self.rf.controls[0].control, fd.Function) is False: 47 | raise RuntimeError("Only control of type Function is possible for MMA") 48 | 49 | control_funcspace = self.rf.controls[0].control.function_space() 50 | self.mesh = control_funcspace.mesh() 51 | control_elem = control_funcspace.ufl_element() 52 | 53 | supported_fe = ["DQ", "Discontinuous Lagrange"] 54 | mass_matrix_support = True 55 | if control_elem.family() == "TensorProductElement": 56 | sub_elem = control_elem.sub_elements() 57 | if ( 58 | sub_elem[0].family() not in supported_fe 59 | or sub_elem[0].degree() != 0 60 | or sub_elem[1].family() not in supported_fe 61 | or sub_elem[1].degree() != 0 62 | ): 63 | mass_matrix_support = False 64 | elif control_elem.family() not in supported_fe or control_elem.degree() != 0: 65 | mass_matrix_support = False 66 | 67 | if parameters.get("norm") == "L2": 68 | if mass_matrix_support: 69 | with stop_annotating(): 70 | self.Mdiag = fd.assemble( 71 | fd.TrialFunction(control_funcspace) 72 | * fd.TestFunction(control_funcspace) 73 | * fd.dx, 74 | diagonal=True, 75 | ).dat.data_ro 76 | else: 77 | fd.warning( 78 | "Only zero degree Discontinuous Galerkin function space is supported for norm = L2" 79 | ) 80 | self.Mdiag = numpy.ones(self.rf.controls[0].control.dat.data_ro.size) 81 | else: 82 | self.Mdiag = numpy.ones(self.rf.controls[0].control.dat.data_ro.size) 83 | 84 | self.__build_mma_problem() 85 | self.__set_parameters() 86 | 87 | self.change = 0.0 88 | self.f0val = 0.0 89 | self.g0val = [[0.0] for _ in range(parameters["m"])] 90 | self.loop = 0 91 | 92 | def __set_parameters(self): 93 | """Set some basic parameters from the parameters dictionary that the user 94 | passed in, if any.""" 95 | param_defaults = { 96 | "m": 1, 97 | "n": 1, 98 | "Mdiag": False, 99 | "tol": 1e-8, 100 | "rfunctol": 1e-8, 101 | "accepted_tol": 1e-4, 102 | "maximum_iterations": 100, 103 | "asyinit": 0.5, 104 | "asyincr": 1.2, 105 | "asydecr": 0.7, 106 | "albefa": 0.1, 107 | "move": 0.1, 108 | "epsimin": 1.0e-05, 109 | "raa0": 1.0e-05, 110 | "xmin": [], 111 | "xmax": [], 112 | "a0": 1.0, 113 | "a": [], 114 | "c": [], 115 | "d": [], 116 | "IP": 0, 117 | "norm": "L2", 118 | "gcmma": False, 119 | "output_dir": "./", 120 | "restart_file": False, 121 | } 122 | if self.parameters is not None: 123 | for key in self.parameters.keys(): 124 | if key not in param_defaults.keys(): 125 | raise ValueError( 126 | "Don't know how to deal with parameter %s (a %s)" 127 | % (key, self.parameters[key].__class__) 128 | ) 129 | 130 | for (prop, default) in param_defaults.items(): 131 | self.parameters[prop] = self.parameters.get(prop, default) 132 | else: 133 | self.parameters = param_defaults 134 | 135 | def __build_mma_problem(self): 136 | """Build the pyipopt problem from the OptimizationProblem instance.""" 137 | 138 | self.rf = self.problem.reduced_functional 139 | assert len(self.rf.controls) == 1, "Only one control is possible for MMA" 140 | assert isinstance( 141 | self.rf.controls[0].control, fd.Function 142 | ), "Only control of type Function is possible for MMA" 143 | 144 | (self.lb, self.ub) = self.__get_bounds() 145 | (nconstraints, self.fun_g, self.jac_g) = self.__get_constraints() 146 | 147 | def __get_bounds(self): 148 | r"""Convert the bounds into the format accepted by MMA (two numpy arrays, 149 | one for the lower bound and one for the upper).""" 150 | 151 | bounds = self.problem.bounds 152 | 153 | if bounds is not None: 154 | lb_list = [] 155 | ub_list = [] # a list of numpy arrays, one for each control 156 | 157 | for (bound, control) in zip(bounds, self.rf.controls): 158 | general_lb, general_ub = bound # could be float, Constant, or Function 159 | 160 | if isinstance(control.control, fd.Function): 161 | n_local_control = control.control.dat.data_ro.size 162 | elif isinstance(control.control, (fd.Constant, AdjFloat)): 163 | n_local_control = 1 164 | else: 165 | raise TypeError( 166 | f"Type of control: {type(control.control)} not supported by pyMMAopt" 167 | ) 168 | 169 | if isinstance(general_lb, (float, int)): 170 | lb = numpy.array([float(general_lb)] * n_local_control) 171 | else: 172 | with general_lb.dat.vec_ro as lb_v: 173 | lb = lb_v.array 174 | 175 | lb_list.append(lb) 176 | 177 | if isinstance(general_ub, (float, int)): 178 | ub = numpy.array([float(general_ub)] * n_local_control) 179 | else: 180 | with general_ub.dat.vec_ro as ub_v: 181 | ub = ub_v.array 182 | 183 | ub_list.append(ub) 184 | 185 | ub = numpy.concatenate(ub_list) 186 | lb = numpy.concatenate(lb_list) 187 | 188 | else: 189 | # Unfortunately you really need to specify bounds, I think?! 190 | ncontrols = len(self.rf.get_controls()) 191 | max_float = numpy.finfo(numpy.double).max 192 | ub = numpy.array([max_float] * ncontrols) 193 | 194 | min_float = numpy.finfo(numpy.double).min 195 | lb = numpy.array([min_float] * ncontrols) 196 | 197 | return (lb, ub) 198 | 199 | def __get_constraints(self): 200 | constraint = self.problem.constraints 201 | 202 | if constraint is None: 203 | # The length of the constraint vector 204 | nconstraints = 0 205 | 206 | # The bounds for the constraint 207 | empty = numpy.array([], dtype=float) 208 | 209 | # The constraint function, should do nothing 210 | def fun_g(x, user_data=None): 211 | return empty 212 | 213 | # The constraint Jacobian 214 | def jac_g(x, flag, user_data=None): 215 | if not flag: 216 | return empty 217 | 218 | rows = numpy.array([], dtype=int) 219 | cols = numpy.array([], dtype=int) 220 | return (rows, cols) 221 | 222 | return (nconstraints, fun_g, jac_g) 223 | else: 224 | # The length of the constraint vector 225 | nconstraints = constraint._get_constraint_dim() 226 | # The constraint function 227 | 228 | def fun_g(x, user_data=None): 229 | return numpy.array(constraint.function(x), dtype=float) 230 | 231 | # The constraint Jacobian: 232 | # flag = True means 'tell me the sparsity pattern'; 233 | # flag = False means 'give me the damn Jacobian'. 234 | 235 | def jac_g(x, user_data=None): 236 | return constraint.jacobian(x) 237 | 238 | return (nconstraints, fun_g, jac_g) 239 | 240 | def solve( 241 | self, xold1_func=None, xold2_func=None, low_func=None, upp_func=None, loop=0 242 | ): 243 | assert ( 244 | xold1_func is None 245 | and xold2_func is None 246 | and low_func is None 247 | and upp_func is None 248 | ) or (xold1_func and xold2_func and low_func and upp_func) 249 | 250 | parameters = self.parameters 251 | tol = parameters["tol"] 252 | rfunctol = parameters["rfunctol"] 253 | # Initial estimation 254 | control_function = self.rf.controls[0].control 255 | 256 | if not xold1_func: 257 | xold1_func = fd.Function(control_function.function_space()) 258 | xold2_func = fd.Function(control_function.function_space()) 259 | low_func = fd.Function(control_function.function_space()) 260 | upp_func = fd.Function(control_function.function_space()) 261 | 262 | if parameters.get("restart_file", None): 263 | with HDF5File(parameters["restart_file"], "r") as checkpoint: 264 | checkpoint.read(control_function, "/control") 265 | checkpoint.read(xold1_func, "/xold1_func") 266 | checkpoint.read(xold2_func, "/xold2_func") 267 | checkpoint.read(low_func, "/low_func") 268 | checkpoint.read(upp_func, "/upp_func") 269 | 270 | with control_function.dat.vec_ro as control_vec: 271 | a_np = control_vec.array 272 | 273 | xold1 = func_to_vec(xold1_func) 274 | xold2 = func_to_vec(xold2_func) 275 | low = func_to_vec(low_func) 276 | upp = func_to_vec(upp_func) 277 | 278 | import numpy as np 279 | 280 | parameters["xmin"] = self.lb 281 | parameters["xmax"] = self.ub 282 | parameters["n"] = control_function.dat.data_ro.size 283 | parameters["Mdiag"] = self.Mdiag 284 | itermax = parameters["maximum_iterations"] 285 | 286 | # Create an optimizer client 287 | clientOpt = MMAClient(parameters) 288 | # 'asyinit':0.2,'asyincr':0.8,'asydecr':0.3 289 | 290 | change_arr = [] 291 | 292 | a_function = control_function.copy(deepcopy=True) 293 | 294 | def receive_signal(signum, stack): 295 | copy_vec_into_funct(xold1_func, xold1) 296 | copy_vec_into_funct(xold2_func, xold2) 297 | copy_vec_into_funct(low_func, low) 298 | copy_vec_into_funct(upp_func, upp) 299 | 300 | with HDF5File( 301 | f"{parameters['output_dir']}/checkpoint_iter_{loop}.h5", "w" 302 | ) as checkpoint: 303 | checkpoint.write(a_function, "/control") 304 | checkpoint.write(xold1_func, "/xold1_func") 305 | checkpoint.write(xold2_func, "/xold2_func") 306 | checkpoint.write(low_func, "/low_func") 307 | checkpoint.write(upp_func, "/upp_func") 308 | 309 | signal.signal(signal.SIGUSR1, receive_signal) 310 | 311 | def eval_f(a_np): 312 | with a_function.dat.vec as a_vec: 313 | a_vec.array_w = a_np 314 | return self.rf(a_function) 315 | 316 | def eval_g(a_np): 317 | with a_function.dat.vec as a_vec: 318 | a_vec.array_w = a_np 319 | return -1.0 * self.fun_g(a_function) 320 | 321 | n = parameters["n"] 322 | m = parameters["m"] 323 | dg0dx = np.empty([m, n]) 324 | df0dx = np.empty([n]) 325 | comm = MPI.COMM_WORLD 326 | 327 | f0val = eval_f(a_np) 328 | g0val = eval_g(a_np).flatten() 329 | 330 | change = 1.0 331 | rfunc_change = 1.0 332 | prev_f0val = f0val 333 | while change > tol and loop <= itermax and rfunc_change > rfunctol: 334 | t0 = time.time() 335 | if loop % 10 == 0 and loop > 0: 336 | TSFCKernel._cache.clear() 337 | GlobalKernel._cache.clear() 338 | gc.collect() 339 | petsc4py.PETSc.garbage_cleanup(self.mesh._comm) 340 | petsc4py.PETSc.garbage_cleanup(self.mesh.comm) 341 | 342 | # Gradients 343 | df0dx_func = self.rf.derivative() 344 | jac = self.jac_g(a_function) 345 | 346 | # Copy into the numpy arrays 347 | with df0dx_func.dat.vec_ro as df_vec: 348 | df0dx[:] = df_vec.array 349 | for j, jac_j in enumerate(jac): 350 | with jac_j[0].dat.vec_ro as jac_vec: 351 | dg0dx[j, :] = -1.0 * jac_vec.array 352 | 353 | # move limits 354 | clientOpt.xmin = self.lb 355 | clientOpt.xmax = self.ub 356 | 357 | (xmma, y, z, lam, low, upp, factor, f0val, g0val,) = clientOpt.mma( 358 | a_np, 359 | xold1, 360 | xold2, 361 | low, 362 | upp, 363 | f0val, 364 | g0val, 365 | df0dx, 366 | dg0dx, 367 | loop, 368 | eval_f=eval_f, 369 | eval_g=eval_g, 370 | ) 371 | 372 | kkt_norm = clientOpt.residualKKTPrimal( 373 | xmma, 374 | y, 375 | z, 376 | lam, 377 | df0dx, 378 | g0val, 379 | dg0dx, 380 | ) 381 | 382 | local_change = np.abs(np.max(xmma - xold1)) 383 | change = comm.allreduce(local_change, op=MPI.MAX) 384 | rfunc_change = abs(prev_f0val - f0val) / abs(prev_f0val) 385 | prev_f0val = f0val 386 | # update design variables 387 | xold2 = np.copy(xold1) 388 | xold1 = np.copy(a_np) 389 | a_np = np.copy(xmma) 390 | loop = loop + 1 391 | 392 | PETSc.Sys.Print("It: {it}, obj: {obj} ".format(it=loop, obj=f0val), end="") 393 | PETSc.Sys.Print( 394 | "".join([f"g[{index}]: {value} " for index, value in enumerate(g0val)]) 395 | ) 396 | # PETSc.Sys.Print(" Inner iterations: {:d}".format(inner_it), end="") 397 | PETSc.Sys.Print(" kkt: {:6f}".format(kkt_norm), end="") 398 | PETSc.Sys.Print(" change: {:.6f}".format(change), end="") 399 | PETSc.Sys.Print(" rel obj change: {:.6f}".format(rfunc_change)) 400 | 401 | change_arr.append(change) 402 | self.change = change 403 | self.f0val = f0val 404 | self.g0val = g0val 405 | self.loop = loop 406 | 407 | # print(f"rank: {rank} array {a_np}") 408 | # if np.all(np.array(change_arr[-10:]) < accepted_tol): 409 | # break 410 | print(f"Time per iteration: {time.time() - t0}") 411 | 412 | copy_vec_into_funct(a_function, a_np) 413 | copy_vec_into_funct(xold1_func, xold1) 414 | copy_vec_into_funct(xold2_func, xold2) 415 | copy_vec_into_funct(low_func, low) 416 | copy_vec_into_funct(upp_func, upp) 417 | # self.rf.set_local(new_params, a_np) 418 | PETSc.Sys.Print( 419 | "Optimization finished with change: {0:.5f} and iterations: {1}".format( 420 | change, loop 421 | ) 422 | ) 423 | results = { 424 | "control": self.rf.controls.delist([a_function]), 425 | "xold1": xold1_func, 426 | "xold2": xold2_func, 427 | "low": low_func, 428 | "upp": upp_func, 429 | "loop": loop, 430 | } 431 | return results 432 | 433 | def current_state(self): 434 | return ( 435 | "It: {it}, obj: {obj:.3f} ".format(it=self.loop, obj=self.f0val) 436 | + "".join( 437 | [*(map("g[{0[0]}]: {0[1][0]:.3e} ".format, enumerate(self.g0val)))] 438 | ) 439 | + " change: {:.3f}\n".format(self.change) 440 | ) 441 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /pyMMAopt/mma.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import copy 3 | import numexpr as ne 4 | from firedrake.petsc import PETSc 5 | from mpi4py import MPI 6 | from firedrake import COMM_WORLD, warning 7 | 8 | 9 | def print(x): 10 | return PETSc.Sys.Print(x, comm=COMM_WORLD) 11 | 12 | 13 | class DesignState(object): 14 | state_args = [ 15 | "x", 16 | "y", 17 | "z", 18 | "lam", 19 | "xsi", 20 | "eta", 21 | "mu", 22 | "zet", 23 | "s", 24 | ] 25 | 26 | def __init__(self, *args, **kwargs): 27 | for k, v in kwargs.items(): 28 | assert k in self.state_args, f"Variable {k} is not admitted" 29 | setattr(self, k, v) 30 | 31 | 32 | class MMAClient(object): 33 | def __init__(self, parameters): 34 | """ 35 | This package performs one MMA-iteration and solves the nonlinear 36 | programming problem written in the form: 37 | Minimize f_0(x) + a_0*z + sum( c_i*y_i + 0.5*d_i*(y_i)^2 ) 38 | subject to f_i(x) - a_i*z - y_i <= 0, i = 1,...,m 39 | xmin_j <= x_j <= xmax_j, j = 1,...,n 40 | z >= 0, y_i >= 0, i = 1,...,m 41 | 42 | At a given iteration, the moving lower "low" and upper "upp" 43 | asymptotes are updated as follows: 44 | * the first two iterations: 45 | low_j = x_j - asyinit * (xmax - xmin) 46 | upp_j = x_j + asyinit * (xmax - xmin) 47 | * the later iterations: 48 | low_j = x_j - gamma_j * (xold_j - low_j) 49 | upp_j = x_j + gamma_j * (upp_j - xold_j) 50 | with 51 | zzz = (xval-xold1)*(xold1-xold2) 52 | gamma_j = asyincr if zzz>0; asydecr if zzz<0; 1 otherwise 53 | and finally 54 | low_j = maximum(low_j, x_j - 10*(xmax_j-xmin_j)) 55 | low_j = minimum(low_j, x_j - 0.01*(xmax_j-xmin_j)) 56 | upp_j = minimum(upp_j, x_j + 10*(xmax_j-xmin_j)) 57 | upp_j = maximum(upp_j, x_j + 0.01*(xmax_j-xmin_j)) 58 | 59 | All the parameters are provided in a dictionnary "parameter" s.t. 60 | "parameter = { 61 | m: "number of constraints", 62 | n: "number of variables x_j", 63 | xmin: "list with the lower bounds for the variables x_j", 64 | xmax: "list with the upper bounds for the variables x_j", 65 | a0: "constant in the term a_0*z", 66 | a: "list with the constants a_i in the terms a_i*z", 67 | c: "list with the constants c_i in the terms c_i*y_i", 68 | d: "list with the constants d_i in the terms 0.5*d_i*(y_i)^2", 69 | asyinit: "constant in the term update of low and upp", 70 | asyincr: "constant in the term update of low and upp", 71 | asydecr: "constant in the term update of low and upp", 72 | albefa: "constant in the term update of low and upp" 73 | move:"constant in the term update of low and upp" 74 | } 75 | """ 76 | param_defaults = { 77 | "m": 1, 78 | "n": 1, 79 | "asyinit": 0.5, 80 | "asyincr": 1.2, 81 | "asydecr": 0.7, 82 | "albefa": 0.1, 83 | "move": 0.1, 84 | "epsimin": 1.0e-05, 85 | "raa0": 1.0e-05, 86 | "xmin": [], 87 | "xmax": [], 88 | "a0": 1.0, 89 | "a": [], 90 | "c": [], 91 | "d": [], 92 | "IP": 0, 93 | "Mdiag": None, 94 | "gcmma": True, 95 | } 96 | 97 | # create the attributes 98 | for (prop, default) in param_defaults.items(): 99 | setattr(self, prop, parameters.get(prop, default)) 100 | self.local_n = len(self.xmin) 101 | if self.m > self.local_n: 102 | raise RuntimeError( 103 | "This MMA implementation only handles a number of constraints smaller than the number of design variables" 104 | ) 105 | self.xmin = np.array(self.xmin) 106 | self.xmax = np.array(self.xmax) 107 | self.comm = MPI.COMM_WORLD 108 | 109 | # TODO if there are two variables per cell, the volume will be twice as big... 110 | # So far, this is not allowed by the element check in MMASolver 111 | local_volume = np.sum(self.Mdiag) 112 | self.volume = self.comm.allreduce(local_volume, op=MPI.SUM) 113 | print(f"Volume for MMA is: {self.volume}") 114 | 115 | # clasical configuration when parameters are unspecified 116 | if len(self.a) == 0: 117 | self.a = np.array([0.0] * self.m) 118 | if len(self.c) == 0: 119 | self.c = np.array([1000.0] * self.m) 120 | if len(self.d) == 0: 121 | self.d = np.array([1.0] * self.m) 122 | 123 | def iPrint(self, msgS, msg, level): 124 | if self.IP > level: 125 | print( 126 | str(" " * level) 127 | + " ".join(msgS[k] + ": {}".format(v) for k, v in enumerate(msg)) 128 | ) 129 | 130 | def residualKKTPrimal( 131 | self, 132 | x, 133 | y, 134 | z, 135 | lam, 136 | df0dx, 137 | fval, 138 | dfdx, 139 | ): 140 | 141 | residual_gradients = df0dx + np.dot(np.transpose(dfdx), lam) 142 | 143 | mu_min = np.where(residual_gradients > 0.0, residual_gradients, 0.0) 144 | mu_min *= (self.xmin - x) * np.sqrt(self.Mdiag) 145 | mu_max = np.where(residual_gradients < 0.0, -residual_gradients, 0.0) 146 | mu_max *= (self.xmax - x) * np.sqrt(self.Mdiag) 147 | norm2_grad = mu_min**2 + mu_max**2 148 | local_norm2 = np.sum(norm2_grad) 149 | norm2 = self.comm.allreduce(local_norm2, op=MPI.SUM) 150 | 151 | residual_constraints = fval - self.a * z - y 152 | residual_constraints = np.where( 153 | residual_constraints < 0.0, lam * residual_constraints, residual_constraints 154 | ) 155 | return np.sqrt(np.sum(residual_constraints**2) + norm2) 156 | 157 | def resKKT( 158 | self, 159 | alfa, 160 | beta, 161 | low, 162 | upp, 163 | p0, 164 | q0, 165 | P, 166 | Q, 167 | b, 168 | design_state, 169 | epsi, 170 | ): 171 | x = design_state.x 172 | y = design_state.y 173 | z = design_state.z 174 | lam = design_state.lam 175 | xsi = design_state.xsi 176 | eta = design_state.eta 177 | mu = design_state.mu 178 | s = design_state.s 179 | zet = design_state.zet 180 | z = design_state.z 181 | 182 | Mdiag = self.Mdiag 183 | ux1 = upp - x 184 | xl1 = x - low 185 | ux2 = ux1 * ux1 186 | xl2 = xl1 * xl1 187 | uxinv1 = 1.0 / ux1 188 | xlinv1 = 1.0 / xl1 189 | plam = p0 + np.dot(P.T, lam) 190 | qlam = q0 + np.dot(Q.T, lam) 191 | local_gvec = (P * self.Mdiag).dot(uxinv1) + (Q * self.Mdiag).dot(xlinv1) 192 | gvec = self.comm.allreduce(local_gvec, op=MPI.SUM) 193 | dpsidx = ne.evaluate("plam / ux2 - qlam / xl2") 194 | 195 | def global_res_norm_square(local_residual): 196 | local_residuNorm = ne.evaluate("sum(local_residual ** 2)") 197 | residuNorm = self.comm.allreduce(local_residuNorm, op=MPI.SUM) 198 | return residuNorm 199 | 200 | def global_residual_max(local_residual): 201 | local_residuMax = np.linalg.norm(local_residual, np.inf) 202 | residuMax = self.comm.allreduce(local_residuMax, op=MPI.MAX) 203 | return residuMax 204 | 205 | # rex 206 | local_residu_x = ne.evaluate("(dpsidx * Mdiag - Mdiag*xsi + Mdiag*eta)") 207 | residu_x_norm = global_res_norm_square( 208 | ne.evaluate("local_residu_x / sqrt(Mdiag)") 209 | ) # This components is in the dual space, the norm has 210 | # to be weighted b the inverse of the mass matrix a.T * M^{-1} * a 211 | # do a sqrt if you're going to do **2 later 212 | residu_x_max = global_residual_max(local_residu_x) 213 | # rey 214 | residu_y = self.c + self.d * y - mu - lam 215 | residu_y_norm = np.sum(residu_y**2) 216 | residu_y_max = np.linalg.norm(residu_y, np.inf) 217 | # rez 218 | residu_z = self.a0 - zet - np.dot(self.a, lam) 219 | residu_z_norm = residu_z**2 220 | residu_z_max = np.abs(residu_z) 221 | # relam 222 | residu_lam = gvec - self.a * z - y + s + b 223 | residu_lam_norm = np.sum(residu_lam**2) 224 | residu_lam_max = np.linalg.norm(residu_lam, np.inf) 225 | # rexsi 226 | local_residu_xsi = ne.evaluate("(xsi * (x - alfa) - epsi) * sqrt(Mdiag)") 227 | residu_xsi_norm = global_res_norm_square(local_residu_xsi) 228 | residu_xsi_max = global_residual_max(local_residu_xsi) 229 | # reeta 230 | local_residu_eta = ne.evaluate("(eta * (beta - x) - epsi)* sqrt(Mdiag)") 231 | residu_eta_norm = global_res_norm_square(local_residu_eta) 232 | residu_eta_max = global_residual_max(local_residu_eta) 233 | # remu 234 | residu_mu = mu * y - epsi 235 | residu_mu_norm = np.sum(residu_mu**2) 236 | residu_mu_max = np.linalg.norm(residu_mu, np.inf) 237 | # rezet 238 | residu_zet = zet * z - epsi 239 | residu_zet_norm = residu_zet**2 240 | residu_zet_max = np.abs(residu_zet) 241 | # res 242 | residu_s = lam * s - epsi 243 | residu_s_norm = np.sum(residu_s**2) 244 | residu_s_max = np.linalg.norm(residu_s, np.inf) 245 | 246 | residu_norm = np.sqrt( 247 | residu_x_norm 248 | + residu_y_norm 249 | + residu_lam_norm 250 | + residu_xsi_norm 251 | + residu_eta_norm 252 | + residu_mu_norm 253 | + residu_s_norm 254 | + residu_z_norm 255 | + residu_zet_norm 256 | ) 257 | residu_max = np.max( 258 | ( 259 | residu_x_max, 260 | residu_y_max, 261 | residu_lam_max, 262 | residu_xsi_max, 263 | residu_eta_max, 264 | residu_mu_max, 265 | residu_s_max, 266 | residu_z_max, 267 | residu_zet_max, 268 | ) 269 | ) 270 | 271 | return residu_norm, residu_max 272 | 273 | def preCompute(self, alfa, beta, low, upp, p0, q0, P, Q, b, design_state, epsi): 274 | x = design_state.x 275 | y = design_state.y 276 | z = design_state.z 277 | lam = design_state.lam 278 | xsi = design_state.xsi 279 | eta = design_state.eta 280 | mu = design_state.mu 281 | s = design_state.s 282 | zet = design_state.zet 283 | z = design_state.z 284 | 285 | # delx,dely,delz,dellam,diagx,diagy,diagxinv,diaglamyi,GG): 286 | invxalpha = ne.evaluate("1 / (x - alfa)") 287 | invxbeta = ne.evaluate("1 / (beta - x)") 288 | ux1 = upp - x 289 | xl1 = x - low 290 | ux2 = ux1 * ux1 291 | xl2 = xl1 * xl1 292 | ux3 = ux1 * ux2 293 | xl3 = xl1 * xl2 294 | uxinv1 = 1.0 / ux1 295 | xlinv1 = 1.0 / xl1 296 | uxinv2 = 1.0 / ux2 297 | xlinv2 = 1.0 / xl2 298 | plam = p0 + lam.dot(P) 299 | qlam = q0 + lam.dot(Q) 300 | local_gvec = (P * self.Mdiag).dot(uxinv1) + (Q * self.Mdiag).dot(xlinv1) 301 | gvec = self.comm.allreduce(local_gvec, op=MPI.SUM) 302 | Mdiag = self.Mdiag 303 | GG = ne.evaluate("uxinv2 * P * Mdiag - xlinv2 * Q * Mdiag") 304 | dpsidx = ne.evaluate("plam * uxinv2 - qlam * xlinv2") 305 | delx = ne.evaluate( 306 | "dpsidx * Mdiag - Mdiag * epsi * invxalpha + Mdiag * epsi * invxbeta" 307 | ) 308 | diagx = ne.evaluate( 309 | "2 * (plam / ux3 + qlam / xl3) * Mdiag + Mdiag * xsi * invxalpha + Mdiag * eta * invxbeta" 310 | ) 311 | diagxinv = 1.0 / diagx 312 | 313 | dely = self.c + self.d * y - lam - epsi / y 314 | delz = self.a0 - np.dot(self.a, lam) - epsi / z 315 | dellam = gvec - self.a * z - y + b + epsi / lam 316 | diagy = self.d + mu / y 317 | diagyinv = 1.0 / diagy 318 | diaglam = s / lam 319 | diaglamyi = diaglam + diagyinv 320 | 321 | return delx, dely, delz, dellam, diagx, diagy, diagxinv, diaglamyi, GG 322 | 323 | def JacDual(self, diagxinvGG, diaglamyi, GG, z, zet): 324 | """ 325 | JAC = [Alam a 326 | a' -zet/z ] 327 | """ 328 | local_Alam = np.dot(diagxinvGG, GG.T) 329 | Alam = self.comm.allreduce(local_Alam, op=MPI.SUM) 330 | mm = range(0, self.m) 331 | Alam[mm, mm] += diaglamyi 332 | jac = np.empty(shape=(self.m + 1, self.m + 1), dtype=float) 333 | jac[0 : self.m, 0 : self.m] = Alam 334 | jac[self.m, 0 : self.m] = self.a 335 | jac[self.m, self.m] = -zet / z 336 | jac[0 : self.m, self.m] = self.a 337 | 338 | return jac 339 | 340 | def RHSdual(self, dellam, delx, dely, delz, diagxinvGG, diagy, GG): 341 | rhs = np.empty(shape=(self.m + 1,), dtype=float) 342 | local_diagxinvGG_delx = diagxinvGG.dot(delx) 343 | diagxinvGG_delx = self.comm.allreduce(local_diagxinvGG_delx, op=MPI.SUM) 344 | rhs[0 : self.m] = dellam + dely / diagy - diagxinvGG_delx 345 | rhs[self.m] = delz 346 | return rhs 347 | 348 | def getNewPoint( 349 | self, 350 | design_state_old, 351 | dx, 352 | dy, 353 | dz, 354 | dlam, 355 | dxsi, 356 | deta, 357 | dmu, 358 | dzet, 359 | ds, 360 | step, 361 | ): 362 | xold = design_state_old.x 363 | yold = design_state_old.y 364 | zold = design_state_old.z 365 | lamold = design_state_old.lam 366 | xsiold = design_state_old.xsi 367 | etaold = design_state_old.eta 368 | muold = design_state_old.mu 369 | sold = design_state_old.s 370 | zetold = design_state_old.zet 371 | zold = design_state_old.z 372 | 373 | x = xold + step * dx 374 | y = yold + step * dy 375 | z = zold + step * dz 376 | lam = lamold + step * dlam 377 | xsi = xsiold + step * dxsi 378 | eta = etaold + step * deta 379 | mu = muold + step * dmu 380 | zet = zetold + step * dzet 381 | s = sold + step * ds 382 | 383 | design_state = DesignState( 384 | x=x, y=y, z=z, lam=lam, xsi=xsi, eta=eta, mu=mu, zet=zet, s=s 385 | ) 386 | 387 | return design_state 388 | 389 | def subsolvIP(self, alfa, beta, low, upp, p0, q0, P, Q, b): 390 | """ 391 | This function subsolv solves the MMA subproblem with interior 392 | point method: 393 | 394 | minimize SUM[ p0j/(uppj-xj) + q0j/(xj-lowj) ] + a0*z + 395 | + SUM[ ci*yi + 0.5*di*(yi)^2 ], 396 | 397 | subject to SUM[ pij/(uppj-xj) + qij/(xj-lowj) ] - ai*z - yi <= bi, 398 | alfaj <= xj <= betaj, yi >= 0, z >= 0. 399 | 400 | Input: m, n, low, upp, alfa, beta, p0, q0, P, Q, a0, a, b, c, d. 401 | Output: xmma,ymma,zmma, slack variables and Lagrange multiplers. 402 | """ 403 | # Initialize the variable values 404 | epsi = 1 405 | x = 0.5 * (alfa + beta) 406 | y = np.ones([self.m]) 407 | z = 1 408 | lam = np.ones([self.m]) 409 | xsi = 1.0 / (x - alfa) 410 | xsi = np.maximum(xsi, 1.0) 411 | eta = np.maximum(1.0 / (beta - x), 1.0) 412 | mu = np.maximum(np.ones([self.m]), 0.5 * self.c) 413 | zet = 1 414 | s = np.ones([self.m]) 415 | epsiIt = 1 416 | 417 | design_state = DesignState( 418 | x=x, y=y, z=z, lam=lam, xsi=xsi, eta=eta, mu=mu, zet=zet, s=s 419 | ) 420 | 421 | if self.IP > 0: 422 | print(str("*" * 80)) 423 | 424 | while epsi > self.epsimin: # Loop over epsilon 425 | self.iPrint(["Interior Point it.", "epsilon"], [epsiIt, epsi], 0) 426 | 427 | # compute residual 428 | residuNorm, residuMax = self.resKKT( 429 | alfa, 430 | beta, 431 | low, 432 | upp, 433 | p0, 434 | q0, 435 | P, 436 | Q, 437 | b, 438 | design_state, 439 | epsi, 440 | ) 441 | 442 | # Solve the NL KKT problem for a given epsilon 443 | it_NL = 1 444 | relaxloopEpsi = [] 445 | while residuNorm > 0.9 * epsi and it_NL < 200: 446 | self.iPrint( 447 | ["NL it.", "Norm(res)", "Max(|res|)"], 448 | [it_NL, residuNorm, residuMax], 449 | 1, 450 | ) 451 | 452 | # precompute useful data -> time consuming!!! 453 | ( 454 | delx, 455 | dely, 456 | delz, 457 | dellam, 458 | diagx, 459 | diagy, 460 | diagxinv, 461 | diaglamyi, 462 | GG, 463 | ) = self.preCompute( 464 | alfa, 465 | beta, 466 | low, 467 | upp, 468 | p0, 469 | q0, 470 | P, 471 | Q, 472 | b, 473 | design_state, 474 | epsi, 475 | ) 476 | 477 | # assemble and solve the system: dlam or dx 478 | diagxinvGG = diagxinv * GG 479 | AA = self.JacDual(diagxinvGG, diaglamyi, GG, z, zet) 480 | bb = self.RHSdual(dellam, delx, dely, delz, diagxinvGG, diagy, GG) 481 | solut = np.linalg.solve(AA, bb) 482 | 483 | dlam = solut[0 : self.m] 484 | dz = solut[self.m] 485 | dx = -delx * diagxinv - np.dot((diagxinv * GG).T, dlam) 486 | dy = -dely / diagy + dlam / diagy 487 | dxsi = ne.evaluate( 488 | "-xsi + epsi / (x - alfa) - (xsi * dx) / (x - alfa)" 489 | ) 490 | deta = ne.evaluate( 491 | "-eta + epsi / (beta - x) + (eta * dx) / (beta - x)" 492 | ) 493 | dmu = -mu + epsi / y - (mu * dy) / y 494 | dzet = -zet + epsi / z - zet * dz / z 495 | ds = -s + epsi / lam - (s * dlam) / lam 496 | 497 | # store variables 498 | design_state_old = copy.copy(design_state) 499 | 500 | # relaxation of the newton step for staying in feasible region 501 | len_xx = self.local_n * 2 + self.m * 4 + 2 502 | xx = np.zeros(len_xx) 503 | np.concatenate((y, [z], lam, xsi, eta, mu, [zet], s), out=xx) 504 | dxx = np.zeros(len_xx) 505 | np.concatenate((dy, [dz], dlam, dxsi, deta, dmu, [dzet], ds), out=dxx) 506 | 507 | stepxx = ne.evaluate("-1.01 * dxx / xx") 508 | local_stmxx = np.max(stepxx) 509 | stmxx = self.comm.allreduce(local_stmxx, op=MPI.MAX) 510 | stepalfa = ne.evaluate("-1.01 * dx / (x - alfa)") 511 | local_stmalfa = np.max(stepalfa) 512 | stmalfa = self.comm.allreduce(local_stmalfa, op=MPI.MAX) 513 | stepbeta = ne.evaluate("1.01 * dx / (beta - x)") 514 | local_stmbeta = np.max(stepbeta) 515 | stmbeta = self.comm.allreduce(local_stmbeta, op=MPI.MAX) 516 | stmalbe = np.maximum(stmalfa, stmbeta) 517 | stmalbexx = np.maximum(stmalbe, stmxx) 518 | stminv = np.maximum(stmalbexx, 1.0) 519 | step = 1.0 / np.maximum(stmalbexx, 1.0) 520 | itto = 1 521 | resinewNorm = 2 * residuNorm 522 | resinewMax = 1e10 523 | while resinewNorm > residuNorm and itto < 200: 524 | self.iPrint( 525 | ["relax. it.", "Norm(res)", "step"], 526 | [itto, resinewNorm, step], 527 | 2, 528 | ) 529 | # compute new point 530 | design_state = self.getNewPoint( 531 | design_state_old, 532 | dx, 533 | dy, 534 | dz, 535 | dlam, 536 | dxsi, 537 | deta, 538 | dmu, 539 | dzet, 540 | ds, 541 | step, 542 | ) 543 | x = design_state.x 544 | y = design_state.y 545 | z = design_state.z 546 | lam = design_state.lam 547 | xsi = design_state.xsi 548 | eta = design_state.eta 549 | mu = design_state.mu 550 | s = design_state.s 551 | zet = design_state.zet 552 | z = design_state.z 553 | 554 | # compute the residual 555 | resinewNorm, resinewMax = self.resKKT( 556 | alfa, 557 | beta, 558 | low, 559 | upp, 560 | p0, 561 | q0, 562 | P, 563 | Q, 564 | b, 565 | design_state, 566 | epsi, 567 | ) 568 | 569 | # update step 570 | step /= 2.0 571 | itto += 1 572 | 573 | if itto > 198: 574 | warning(f"Line search iteration limit {itto} reached") 575 | 576 | self.iPrint( 577 | ["relax. it.", "Norm(res)", "step"], [itto, resinewNorm, step], 2 578 | ) 579 | 580 | residuNorm = resinewNorm 581 | residuMax = resinewMax 582 | step *= 2.0 583 | it_NL += 1 584 | 585 | if it_NL > 500: 586 | warning(f"Iteration limit of the Newton solver ({it_NL}) reached") 587 | epsi *= 0.1 588 | epsiIt += 1 589 | 590 | if self.IP > 0: 591 | print(str("*" * 80)) 592 | 593 | return x, y, z, lam 594 | 595 | def moveAsymp(self, xval, xold1, xold2, low, upp, iter): 596 | """ 597 | Calculation of the asymptotes low and upp 598 | """ 599 | if iter <= 2: 600 | low = xval - self.asyinit * (self.xmax - self.xmin) 601 | upp = xval + self.asyinit * (self.xmax - self.xmin) 602 | else: 603 | zzz = (xval - xold1) * (xold1 - xold2) 604 | factor = np.ones(self.local_n) 605 | factor[np.where(zzz > 0)] = self.asyincr 606 | factor[np.where(zzz < 0)] = self.asydecr 607 | low = xval - factor * (xold1 - low) 608 | upp = xval + factor * (upp - xold1) 609 | low = np.maximum(low, xval - 10 * (self.xmax - self.xmin)) 610 | low = np.minimum(low, xval - 0.01 * (self.xmax - self.xmin)) 611 | upp = np.minimum(upp, xval + 10 * (self.xmax - self.xmin)) 612 | upp = np.maximum(upp, xval + 0.01 * (self.xmax - self.xmin)) 613 | 614 | return low, upp 615 | 616 | def moveLim(self, iter, xval, xold1, xold2, low, upp, factor): 617 | """ 618 | Calculation of the move limits: alfa and beta 619 | """ 620 | aa = np.maximum( 621 | low + self.albefa * (xval - low), xval - self.move * (self.xmax - self.xmin) 622 | ) 623 | alfa = np.maximum(aa, self.xmin) 624 | aa = np.minimum( 625 | upp - self.albefa * (upp - xval), xval + self.move * (self.xmax - self.xmin) 626 | ) 627 | beta = np.minimum(aa, self.xmax) 628 | 629 | return alfa, beta, factor 630 | 631 | def mmasubMat(self, xval, low, upp, f0val, df0dx, fval, dfdx, rho0, rhoi): 632 | """ 633 | Calculations of p0, q0, P, Q and b. 634 | """ 635 | 636 | xmami = self.xmax - self.xmin 637 | xmamiinv = 1.0 / xmami 638 | ux1 = upp - xval 639 | ux2 = ux1 * ux1 640 | xl1 = xval - low 641 | xl2 = xl1 * xl1 642 | p0 = np.maximum(df0dx, 0.0) 643 | q0 = np.maximum(-df0dx, 0.0) 644 | pq0 = 0.001 * (p0 + q0) + rho0 * xmamiinv 645 | p0 = p0 + pq0 646 | q0 = q0 + pq0 647 | p0 = p0 * ux2 648 | q0 = q0 * xl2 649 | 650 | P = np.maximum(dfdx, 0.0) 651 | Q = np.maximum(-dfdx, 0.0) 652 | PQ = 0.001 * (P + Q) + rhoi[:, np.newaxis] * xmamiinv[np.newaxis, :] 653 | P = ne.evaluate("ux2 * (P + PQ)") 654 | Q = ne.evaluate("xl2 * (Q + PQ)") 655 | ux1inv = ne.evaluate("1.0 / ux1") 656 | xl1inv = ne.evaluate("1.0 / xl1") 657 | 658 | local_b0 = np.dot(p0 * self.Mdiag, ux1inv) + np.dot(q0 * self.Mdiag, xl1inv) 659 | b0 = -self.comm.allreduce(local_b0, op=MPI.SUM) + f0val 660 | 661 | local_b = np.dot(P * self.Mdiag, ux1inv) + np.dot(Q * self.Mdiag, xl1inv) 662 | b = -self.comm.allreduce(local_b, op=MPI.SUM) + fval.T 663 | 664 | return p0, q0, P, Q, b0, b 665 | 666 | def calculate_initial_rho(self, dfdx, xmax, xmin): 667 | local_rho = np.dot(np.abs(dfdx), xmax - xmin) 668 | rho = 0.1 / self.volume * self.comm.allreduce(local_rho, op=MPI.SUM) 669 | if self.gcmma == False: 670 | if isinstance(rho, np.ndarray): 671 | rho.fill(1e-5) 672 | else: 673 | rho = 1e-5 674 | return rho 675 | 676 | def calculate_rho(self, rho, new_fval, fapp, x_inner, x_outer, low, upp): 677 | denom = np.dot( 678 | self.Mdiag, 679 | ( 680 | (upp - low) 681 | * (x_inner - x_outer) ** 2 682 | / ((upp - x_inner) * (x_inner - low) * (self.xmax - self.xmin)) 683 | ), 684 | ) 685 | denom = self.comm.allreduce(denom, op=MPI.SUM) 686 | delta = (new_fval - fapp) / denom 687 | 688 | if not isinstance(fapp, np.ndarray): 689 | delta = np.array([delta]) 690 | rho 691 | 692 | return np.where( 693 | delta > 0, 694 | np.minimum(1.1 * (rho + delta), 10.0 * rho), 695 | rho, 696 | ) 697 | 698 | def convex_approximation(self, x_inner, p, q, b, low, upp): 699 | if len(p.shape) > 1: 700 | local_fapp = np.sum( 701 | self.Mdiag * p / (upp - x_inner) + self.Mdiag * q / (x_inner - low), 1 702 | ) 703 | else: 704 | local_fapp = np.sum( 705 | self.Mdiag * p / (upp - x_inner) + self.Mdiag * q / (x_inner - low) 706 | ) 707 | fapp = self.comm.allreduce(local_fapp, op=MPI.SUM) + b 708 | return fapp 709 | 710 | def condition_check(self, fapp, new_fval): 711 | 712 | if isinstance(fapp, np.ndarray): 713 | assert fapp.size == new_fval.size 714 | else: 715 | fapp = np.array([fapp]) 716 | new_fval = np.array([new_fval]) 717 | 718 | tolerance = 1e-8 719 | 720 | condition = False 721 | for fapp_i, new_fval_i in zip(fapp, new_fval): 722 | print(f"condition: fapp {fapp_i}, new_fval {new_fval_i}") 723 | if fapp_i + tolerance >= new_fval_i: 724 | condition = True 725 | else: 726 | return False 727 | 728 | return condition 729 | 730 | def mma( 731 | self, 732 | xval, 733 | xold1, 734 | xold2, 735 | low, 736 | upp, 737 | f0val, 738 | fval, 739 | df0dx, 740 | dfdx, 741 | iter, 742 | factor=[], 743 | eval_f=None, 744 | eval_g=None, 745 | ): 746 | 747 | # Calculation of the asymptotes low and upp 748 | low, upp = self.moveAsymp(xval, xold1, xold2, low, upp, iter) 749 | 750 | # Calculation of the bounds alfa and beta 751 | alfa, beta, factor = self.moveLim(iter, xval, xold1, xold2, low, upp, factor) 752 | 753 | rho0 = self.calculate_initial_rho(df0dx, self.xmax, self.xmin) 754 | rhoi = self.calculate_initial_rho(dfdx, self.xmax, self.xmin) 755 | 756 | inner_it_max = 100 757 | inner_it = 0 758 | # Apply Riesz map to the gradients 759 | df0dx /= self.Mdiag 760 | dfdx /= self.Mdiag 761 | while inner_it < inner_it_max: 762 | # generate subproblem 763 | p0, q0, P, Q, b0, b = self.mmasubMat( 764 | xval, low, upp, f0val, df0dx, fval, dfdx, rho0, rhoi 765 | ) 766 | print(f"rho0: {rho0}, rhoi: {rhoi}") 767 | 768 | # solve the subproblem 769 | x_inner, y, z, lam = self.subsolvIP(alfa, beta, low, upp, p0, q0, P, Q, b) 770 | 771 | new_f0val = eval_f(x_inner) 772 | new_fval = eval_g(x_inner).flatten() 773 | 774 | f0app = self.convex_approximation(x_inner, p0, q0, b0, low, upp) 775 | fapp = self.convex_approximation(x_inner, P, Q, b, low, upp) 776 | 777 | assert fapp.size == new_fval.size 778 | if self.gcmma == False or ( 779 | self.condition_check(f0app, new_f0val) 780 | and self.condition_check(fapp, new_fval) 781 | ): 782 | break 783 | else: 784 | rho0 = self.calculate_rho( 785 | rho0, new_f0val, f0app, x_inner, xval, low, upp 786 | ) 787 | rhoi = self.calculate_rho(rhoi, new_fval, fapp, x_inner, xval, low, upp) 788 | print(f"Recalculating rho") 789 | 790 | inner_it += 1 791 | 792 | return ( 793 | x_inner, 794 | y, 795 | z, 796 | lam, 797 | low, 798 | upp, 799 | factor, 800 | new_f0val, 801 | new_fval, 802 | ) 803 | --------------------------------------------------------------------------------